matplotlib库
pyplot:
matplotlib.pyplot是绘制各类可视化图形的命令子库
引用方式:import matplotlib.pyplot as plt
plt.plot(x,y) # x,y可以存放元组和数组类型
plt.ylabel() # y轴标签
plt.xlabel() # x轴标签
plt.subplot(x, y, c) # 绘制一个人横x,纵y的区域,在第c个区域绘制
plt.savefig(name, dpi) #保存为PNG格式
plt.show() # 展示
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t)*np.cos(2*np.pi*t)
a = np.arange(0.0,5.0,0.02)
plt.subplot(211)
plt.plot(a,f(a))
plt.subplot(2,1,2)
plt.plot(a,np.cos(2*np.pi*a),'r--')
plt.show()
pyplot虽然是matplotlib库的其中一个,但是内置了大量的图形:
饼状图
使用 plt.pie() 绘制
import matplotlib.pyplot as plt
lables = 'Frogs','Hogs','Dogs','Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0, 0, 0)
plt.pie(sizes, explode = explode, labels = lables, autopct = '%1.1f%%',
shadow = False, startangle = 90)
plt.axis('equal')
plt.show()
直方图
使用 plt.hist() 绘制
matplotlib.pyplot.hist(x, bins=None, range=None, normed=False,
weights=None, cumulative=False, bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False, color=None, label=None,
stacked=False, hold=None, data=None, **kwargs)
这么多参数,我们只需要关注其中几个 示例:
import numpy as np
import matplotlib.pyplot as plt
mu,sigma = 100,20
a = np.random.normal(mu, sigma,size = 100)
plt.hist(a, 10, histtype = 'stepfilled',facecolor = 'b', alpha = 0.5)
plt.title('Histogram')
plt.show()
极坐标图
使用 plt.polar 绘制
import numpy as np
import matplotlib.pyplot as plt
N = 20
theta = np.linspace(0.0,2*np.pi, N, endpoint=False)
radii = 10*np.random.rand(N)
width = np.pi/ 4 * np.random.rand(N)
ax = plt.subplot(111, projection='polar')
bars = ax.bar(theta, radii, width=width, bottom=0.0)
for r,bar in zip(radii, bars):
bar.set_facecolor(plt.cm.viridis(r/10.))
bar.set_alpha(0.5)
plt.show()
散点图
散点图只需要使用plot函数即可
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o')
ax.set_title('Simple Scatter')
plt.show()
|