简介
- 一个python版的matlab绘图接口,以2D为主,支持python、numpy、pandas基本数据结构
- 参考链接:https://matplotlib.org/api/pyplot_api.html
图表窗口
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 图表窗口 plt.show()
plt.plot(np.random.rand(10))
plt.show()
# 散点图
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y)
plt.show()
# 如果不想每次展示图表都调用plt.show()可以添加下面语句
% matplotlib inline
# 可交互魔法窗口
%matplotlib notebook
# 弹出matplotlib控制台
%matplotlib qt5
图表基本元素
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline
df = pd.DataFrame(np.random.rand(10,2), columns=['A', 'B'])
# 设置图表窗口大小
fig = df.plot(figsize=(6, 4))
# 设置图名
plt.title('Interesting Graph')
# 设置图标签
plt.xlabel('Plot Number')
plt.ylabel('Important Var')
# 设置图例 loc表示位置, 'best', 'upper right', 'upper left', lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'
plt.legend(loc = 'upper right')
# 轴边界
plt.xlim([0, 12])
plt.ylim([0, 1.5])
# 轴刻度
plt.xticks(range(10))
plt.yticks([0.2, 0.4, 0.6, 0.8])
# 轴刻度显示
plt.tick_params(bottom='on', top='off', left='on', right='off')
# 轴刻度显示方向设置 'in', 'out', 'inout'
matplotlib.rcParams['xtick.direction']='in'
matplotlib.rcParams['ytick.direction']='in'
# 轴刻度标签, 注意plt没有该方法,只有窗口存在该方法
fig.set_xticklabels('%.1f' %i for i in range(10))
fig.set_yticklabels('%.2f' %i for i in [0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2])
# 坐标轴可见性 'off', 'on'
plt.axis('off')
# 单独控制x,y坐标轴可见性
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
# 一次绘制,多个设置(其中xlabel, ylabel只能单独设置)
df.plot(figsize=(6,4), plt.title='Interesting')
# 元素的可视性
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x,c)
plt.plot(x,s)
# 显示网格, axis:'x', 'y', 'both'
plt.grid(True, linestyle=='--', color='gray', linewidth='0.5', axis='x')
# 注释 plt.text(x, y, txt, fontsize)
plt.text(2, 10, 'value', fontsize = 10)
# 图表保存 支持png,pdf,svg,esps等 dpi是分辨率 bbox_inches是图表需要保存的部分,设置‘tight’则尝试剪除图表周围空白部分 facecolor是背景色 edgecolor是边框线颜色
plt.savefig('C:/Users/pic.png', dpi=400, bbox_inches='tight', facecolor='g', edgecolor='b')
图表样式参数
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.style as psl
%matplotlib inline
# linestyle参数 实线'-', 虚线'--', 点画线'-.', 点':'
plt.plot([i**2 for i in range(100)], linestyle='-.')
# marker参数,显示数据点样式 '.', '。', 'x'等
s = pd.Series(np.random.randn(100).cumsum())
plt.plot(s, marker='+')
# color参数 red-r, green-g, black-k, blue-b, yellow-y
plt.hist(np.random.randn(100), color='g', alpha=0.8)
# style参数,是linestyle、marker、color参数的集合,注意plt.plot中没有style参数
s.plot(style='--go')
# 图表样式
# 查看有哪些样式
print(plt.style.available)
# 使用某个样式
psl.use('seaborn-ticks')
# 整体风格使用手绘样式
plt.xkcd()
子图
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 子图创建方法一
fig = plt.figure(figsize=(10,6), facecolor='gray')
ax1 = fig.add_subplot(2,2,1) # 第一行的左图
plt.plot(np.random.rand(50).cumsum(), 'k--')
ax2 = fig.add_subplot(2,2,2) # 第一行的右图
ax2.hist(np.random.rand(50), alpha=0.5)
# 子图创建方法二
fig, axes = plt.subplots(2,3,figsize=(10, 4))
s = pd.Series(np.random.randn(1000).cumsum())
ax1 = axes[0, 1]
ax1.plot(s)
# plt.subplots 参数调整
fig, axes = plt.subplots(2,2,sharex=True,sharey=True) # sharex,sharey是否共享x,y刻度
for i in range(2):
for j in range(2):
axes[i, j].hist(np.random.randn(200), color='k', alpha=0.5)
plt.subplots_adjust(wspace=0.5, hspace=0.1) # 控制宽度和高度的百分比
基本图表绘制
- 图表类别:线型图、柱状图、密度图、面积图、饼图、直方图、密度图、堆叠直方图、散点图、箱型图
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 通过series生成图表
ts = pd.Series(np.random.randn(30), index=pd.data_range('1/1/2000', periods=30))
ts = ts.cumsum()
ts.plot(kind='line', # 折线图line, 直方图bar, 横向直方图barh, 密度图kde
label='hehe', # 图例标签,DataFrame格式以列名为label
style='--g.', # 风格字符串
color='red', # 颜色
alpha=0.4, # 透明度
use_index=True, # 将索引用为刻度标签,默认为True
rot=45, # 旋转刻度标签,0-360
grid=True, # 显示网格
ylim=[-50,50], # 轴界限
yticks=list(range(-50,50,10)), # 轴刻度
figsize=(8,4), # 图像大小
title='test', # 图名
legend=True # 图例
)
# 填图
x = np.linspace(0, 1, 500)
y1 = np.sin(4*np.pi*x*np.exp(-5*x))
y2 = -np.sin(4*np.pi*x*np.exp(-5*x))
# 函数与坐标轴之间区域填充方法一
axes[0].fill(x, y1, 'r', alpha=0.5, label='y1')
axes[0].fill(x, y2, 'g', alpha=0.5, label='y2')
# 函数与坐标轴之间区域填充方法二
plt.fill(x, y1, 'r', x, y2, 'g', alpha=0.5)
# 两个函数之间区域填充方法
axes[1].fill_between(x, y1, y2, color='b', alpha=0.5, label='area')
# 柱状图
plt.figure(figsize=(10,4))
x=np.arange(10)
y1=np.random.rand(10)
y2=-np.random.rand(10)
plt.bar(x, y1, width=1, facecolor='yellowgreen', edgecolor='white', yerr=y1*0.1) # yerr为y方向error bar
# 面积图
fig, axes = plt.subplots(2, 1, figsize=(8,6))
df1 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.random.rand(10, 4), columns=list('abcd'))
df1.plot.area(colormap='Greens_r', alpha=0.5, ax=axes[0])
df2.plot.area(stacked=False, colormap='Set2', alpha=0.5, ax=axes[1]) # stacked是否堆叠
# 饼图
s = pd.Series(3*np.random.rand(4), index=list('abcd'), name='series')
plt.axis('equal') # 保证长宽相等
plt.pie(s, # 数据
explode=[0.1, 0, 0, 0], # 指定每部分偏移量
labels=s.index, # 标签
colors=['r', 'g', 'b', 'c'], # 颜色
autopct='%.2f%%', # 饼图上数据标签显示方式
pctdistance=0.6, # 每个饼切片的中心和通过autopct生成的文本开始之间的比例
labeldistance=1.2, # 画饼标签的位置,离圆心的直径,默认值1.1
shadow=True, # 阴影
startangle=0, # 开始角度
radius=1.5, # 半径
frame=False) # 画框
# 直方图+密度图
s = pd.Series(np.random.randn(1000))
s.hist(bins = 20, # 箱子的宽度
histtype= 'bar', # 风格:bar, barstacked, step, stepfilled
align = 'mid', # 对齐方式:'left', 'mid', 'right'
orientation = 'vertical', # 水平还是垂直 'horizontal' 'vertical'
alpha = 0.5,
normed = True) # 标准化
s.plot(kind='kde', style='k--')
# 堆叠直方图
plt.figure(num = 1)
df = pd.DataFrame({'a':np.random.randn(1000)+1, 'b':np.random.randn(1000),
'c':np.random.randn(1000)-1, 'd':np.random.randn(1000)-2},
columns=list('abcd'))
df.plot.hist(stacked=True, bins=20, colormap='Greens_r', alpha=0.5, grid=True) # 四列直方图堆叠在一个axes中
df.hist(bins=50) # 每列单独生成一个直方图
# 散点图
plt.figure(figsize=(8, 6))
x=np.random.randn(1000)
y=np.random.randn(1000)
plt.scatter(x, y, marker='.', s=np.random.randn(1000)*100, cmap='Reds', c=y, alpha=0.8) # cmap是colormap, c是散点的颜色,s是散点的大小
plt.grid()
# 箱型图
fig, axes = plt.subplots(2, 1, figsize=(10, 6))
df = pd.DataFrame(np.random.rand(10, 5), columns=list('ABCDE'))
# boxes:箱线,whiskers:分位数与error bar横线之间竖线的颜色,medians:中位数线颜色,caps: error bar横线颜色
color = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray')
# 箱型图方法一
df.plot.box(ylim=[0, 1.2], grid=True, color=color, ax=axes[0])
df.plot.box(vert=False, positions=[1,4,5,6,8], ax=axes[1], grid=True, color=color) # vert是否垂直,默认True。 position:箱型图占位
# 箱型图方法二
df = pd.DataFrame(np.random.rand(10,2), columns=['col1', 'col2'])
df['X'] = pd.Series(list('AAAAABBBBB'))
df['Y'] = pd.Series(list('ABABABABAB'))
df.boxplot(column=['col1', 'col2'], by=['X','Y']) # by是按指定列值进行分组后绘制对应列箱型图