小项目:数据可视化
Matplotlib库
前奏:
import matplotlib.pyplot as plt
x=[1,2,3]
x1=[2,3,4]
y=[1,2,3,4,5]
z=['com a','com b','com c']
z1=['com A','com B','com C']
plt.bar(z,x,label='bar_1',color='red') #柱状图
plt.bar(z1,x1,label='bar_2',color='blue') #柱状图
#plt.plot(x,y) #线段
plt.title("ABC") #顶部的标签
plt.legend() #标注多个标签
#plt.xlabel x轴的标签,y轴同理
plt.show()
直方图
其中hist是库里一种以分类为主的画图方法。
import matplotlib.pyplot as plt
City_A=[1,2,3,4,5,6,7,8,9,10,11,12]
plt.xlabel('month')
plt.ylabel('sales')
plt.title('sales of company')
bins=[0,11,22,33,44,55,66,77,88,99,100,111,222]
plt.hist(City_A,bins,histtype='bar',rwidth=0.8)
plt.legend()
plt.show()
散点图
import matplotlib.pyplot as plt
x=[1,2,3,4,5,6,7,8,9,10]
y=[1,2,3,1,2,4,5,6,7,8]
plt.scatter(x,y,label='my first scatter',color='r',marker='*')
#marker 是标点的样式
#甚至还可以在后面加size 改变点的大小程度
plt.title('hellow')
plt.legend()
plt.show()
堆栈图
import matplotlib.pyplot as plt
month=[1,2,3,4,5,6,7,8,9]
a=[1,2,3,4,5,6,7,8,9]
b=[2,3,4,5,6,7,8,9,10]
c=[11,22,33,44,55,66,77,88,99]
d=[1,1,1,1,1,1,1,1,20]
plt.stackplot(month,a,b,c,d)
plt.xlabel('month')
plt.ylabel('complany')
plt.legend()
plt.show()
饼状图
import matplotlib.pyplot as plt
sales=[1,4,6,7,9]
name=['A','B','C','D','E']
color=['r','blue','pink','grey','azure']
plt.pie(sales,labels=name,colors=color,startangle=90,
shadow=True,
autopct='%.2f%%',
explode=(0.1,0,0,0,0))
#shadow就是饼状图下面是否有一层阴影
#startangle 是从多少度开始画图
#autopct'%1.2f%% 显示每个圆饼的百分比,%%只是打印一个% 转义字符
# explode 是让某个饼区域移出来数字越大出来的越明显
plt.show()
csv读入数据
import matplotlib.pyplot as plt
import numpy as np
x,y=np.loadtxt('/Users/蔡洪浩/Desktop/1.txt',delimiter=' ',unpack=True)
plt.plot(x,y)
#delimiter 表示由什么分割
#unpack 表示是否为两个不同的类型
plt.xlabel('学分')
plt.ylabel('成绩')
plt.legend()
plt.show()
推荐tushare作为外来接口来传输数据。