要引入的库:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from numpy.random import randn
一个画板多个图,默认最后在一个添加,也可署名(或者用坐标表示):
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)#表示在figure中建立2*2个坐标系,ax1位于第一个坐标中
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax1.hist(randn(100),bins=20,color='k',alpha=0.3)#在ax1上作图
ax2.scatter(np.arange(30),np.arange(30)+3*randn(30))#在ax2上作图
plt.plot(randn(50).cumsum(),"k--")
plt.show()
刻度、标签和标题:
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum())
ticks = ax.set_xticks([0, 250, 500, 750, 1000])
labels = ax.set_xticklabels(["one", "two", "three", "four", "five"], rotation=30, fontsize="small")
ax.set_title("my first matplotlib plot")
ax.set_xlabel('Stages')
plt.show()
图例:
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum(), label="one") # 创建label标签
ax.plot(randn(1000).cumsum(), label="two")
ax.plot(randn(1000).cumsum(), label="three")
ax.legend(loc="best") # loc是用来说明图例的放置位置
plt.show()
在图表中添加图形:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)
cric = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]], color='g', alpha=0.5)
ax.add_patch(rect)
ax.add_patch(cric)
ax.add_patch(pgon)
plt.show()
Pandas作图:
s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
s.plot()
plt.show()
df =pd.DataFrame(np.random.randn(10, 4).cumsum(0), columns=['A', 'B', 'C', 'D'], index=np.arange(0, 100, 10))
df.plot()
plt.show()
柱状图(Seris):
fig, axes = plt.subplots(2, 1)
data = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))
data.plot(kind='bar', ax=axes[0], color='k', alpha=0.7) # 竖直
data.plot(kind='barh', ax=axes[1], color='k', alpha=0.7) # 水平
plt.show()
柱状图(DataFrame),每一行的值分为一组:
fig, axes = plt.subplots(2, 1)
df = pd.DataFrame(np.random.rand(6, 4), index=['one', 'two', 'three', 'four', 'five', 'six'],
columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))
df.plot(kind='bar', ax=axes[0], stacked=False, alpha=0.5) # 不合在一起
df.plot(kind='barh', ax=axes[1], stacked=True, alpha=0.5) # 合在一起
plt.show()
直方图和密度图:
# numpy.random.normal(loc=0.0, scale=1.0, size=None),loc:均值;scale:标准差;size:输出的shape,默认为None
comp1 = np.random.normal(0, 1, size=200) # N(0, 1)
comp2 = np.random.normal(10, 2, size=200) # N(10, 4)
values = pd.Series(np.concatenate([comp1, comp2])) #concatenate函数相当于组合,axis=1表示水平组合,axis=0为垂直组合
values.hist(bins=100, alpha=0.3, color='k', normed=True) # normed=True 是进行拟合的关键
values.plot(kind='kde', style='k--') # kde 表示密度图
plt.show()