画散点图
在数据分析中经常用到画图。
python中的数据分析三大件:
numpy、pandas、pyplpt以下是一个画散点图的例子:
#导入三大件!
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
#读取数据
path='data'+os.sep+'LogiReg_data.txt'#os.sep会自动根据系统环境变成/或\
pdData=pd.read_csv(path,header=None,names=['exam1','exam2','admit'])
print(pdData.shape)
#提取子表
positive=pdData[pdData['admit']==1]
negative=pdData[pdData['admit']==0]
#print(positive.shape)
#选用散点图
def show1():
fig, ax = plt.subplots(figsize=(10, 5))
ax.scatter(positive['exam1'], positive['exam2'], s=10, c='r', marker='o', label='Admitted')
ax.scatter(negative['exam1'], negative['exam2'], s=10, c='b', marker='x', label='Rejected')
# 调整显示
ax.legend()
ax.set_xlabel("Exam1 Score")
ax.set_ylabel("Exam2 Score")
plt.show()
if __name__ == '__main__':
show1()
序号 | 说明 |
---|---|
1 | pdData=pd.read_csv(path,header=None,names=[‘exam1’,‘exam2’,‘admit’])在读入时由于没有列名,自己指定了一个列名 |
2 | positive=(pdData[‘admit’]==1)会返回[‘admit’]列下值为True或False的一张表,positive=pdData[pdData[‘admit’]==1]会把[‘admit’]列下值为True的元素拿出来作为一张子表 |
3 | fig, ax = plt.subplots(figsize=(10, 5))使用subplots可以将子图画在一张图里,figsize=(10, 5)这个参数用于指定图的大小 |
4 | ax.scatter(ag1, ag2, s=10, c=‘r’, marker=‘o’, label=‘Admitted’)#制散点图操作,ag1和ag2以向量的方式传入序列ag1是横坐标,ag2是纵坐标,此处传入positive[‘exam1’], positive[‘exam2’],c指定颜色,marker指定散点符合 |
5 | ax.legend()可以把标签名称显示出来ax.set_ylabel(“Exam2 Score”)指定坐标名称 |