python matplotlib绘图总结

Matplotlib是Python中用的最多的2D图形绘图库,学好Matplotlib的用法可以帮助我们在统计分析中更灵活的展示各种数据的状态,它可与 NumPy 一起使用。

1、创建方式

import matplotlib.pyplot as plt
import numpy as np   # 配合使用
import pandas as pd  # 配合使用

2、图片大小、标题、

plt.figure(figsize=(9, 3))  # 图片大小:长和宽
plt.title("Abnormal point")

3、分图

plt.figure(1, figsize=(9, 3))  # 图1
plt.figure(2, figsize=(9, 3))  # 图2
plt.figure(3, figsize=(9, 3))  # 图3
plt.figure(4, figsize=(9, 3))  # 图4

4、子图 

# 矩阵式排列-两行两列
plt.subplot(2, 2, 1)  # 子图1
plt.subplot(2, 2, 2)  # 子图2
plt.subplot(2, 2, 3)  # 子图3
plt.subplot(2, 2, 4)  # 子图4

5、subplot加主标题和副标题? 

# 有suptitle这个函数,专门生成总标题的
plt.suptitle('Main titile', fontsize=14) 
plt.subplot(2, 2, 1)
plt.title('subtitle1')  # 子图1的标题
plt.subplot(2, 2, 2)
plt.title('subtitle2')  # 子图2的标题
plt.subplot(2, 2, 3)
plt.title('subtitle3')  # 子图3的标题
plt.subplot(2, 2, 4)
plt.title('subtitle4')  # 子图4的标题

6、另一种subplot方法

fig, ax_arr = plt.subplots(4, sharex=True)
fig.set_size_inches(12, 8)
 
pd.Series(data=y, index=x).plot(ax=ax_arr[0], color="b", linestyle='-')
ax_arr[0].set_title("Original sequence")

pd.Series(data=decompose_model.trend, index=x).plot(ax=ax_arr[1], color="c", linestyle='-')
ax_arr[1].set_title("Trend section")
 
pd.Series(data=decompose_model.seasonal, index=x).plot(ax=ax_arr[2], color="g", linestyle='-')
ax_arr[2].set_title("Seasonal section")
 
pd.Series(data=decompose_model.resid, index=x).plot(ax=ax_arr[3], color="r", linestyle='-')
ax_arr[3].set_title("Residual section")

7、子图合并一个图,不知道数量

lens = len(all_sub_graphs)
b = a = int(math.sqrt(lens))
if a*a < lens:
    b = b+1
plot = plt.subplot(a, b, i+1)

8、线条颜色和类型

plt.plot(y, color='b', marker='o')
plt.plot(y, color='b', linestyle='-')

linestyle,marker可选参数参考:https://www.cnblogs.com/darkknightzh/p/6117528.html

9、matplotlib去掉座标轴刻度

 ax.set_axis_off()
 ax.set_xticks([])
 ax.set_yticks([])

10、label图例有中文

plt.rcParams['font.sans-serif']=['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False    # 用来正常显示负号
# 有中文出现的情况,需要u'内容'

11、设置座标轴

ax = plt.gca()
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
ax.set_xlim(xmin, xmax)  # 设置座标轴范围

12、随机颜色

def random_color():
    color_arr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
    color = ""
    for i in range(6):
        color += color_arr[random.randint(0, 14)]
    return "#"+color

13、图例位置

plt.legend(handles = [l1, l2], labels = ['a', 'b'], loc = 'best')

除'best',另外loc属性有:'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'

14、解决linux图片中文乱码

plt.rcParams['font.sans-serif'] = ['simhei']  # 用来正常显示中文标签

还不行就:

import os
from matplotlib import font_manager as fm, rcParams

fig, ax = plt.subplots()
fpath = os.path.join(rcParams["datapath"], "D:/Anaconda3/Lib/site-packages/matplotlib\mpl-data/fonts/ttf/simhei.ttf")  # 需要提前下好字体库
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title(u'中文出来This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This 急急急 the default font', fontproperties=prop)
plt.savefig("chinese.png")

此时图例:

plt.legend(loc="best", prop=prop)

15、画垂直虚线

  • vlines(x, ymin, ymax)
  • hlines(y, xmin, xmax)
plt.vlines(x-values, -5, 100, colors="#808080", linestyles="dashed", label="baseline")

plt.hlines(up_threshold, x[0], x[-1], colors="r", linestyles="dashed")   # 上线
plt.hlines(low_threshold, x[0], x[-1], colors="r", linestyles="dashed")  # 下线

16、直方图画法

plt.hist(data, color='b', alpha=.7)

17、图例legend在图外的画法

ax1 = plt.gca()
box = ax1.get_position() 
ax1.set_position([box.x0, box.y0, box.width, box.height* 0.8])
ax1.legend(loc='center left', bbox_to_anchor=(0.2, 1.12), ncol=3)

18、将Matplotlib图形保存为全屏图像

manager = plt.get_current_fig_manager()
manager.window.showMaximized()

19、tight_layout调整子图参数

tight_layout会自动调整子图参数,调整子图之间的间隔来减少堆叠,使之填充整个图像区域。关键字参数padw_pad或者h_pad,这些参数图像边界和子图之间的额外边距。边距以字体大小单位规定。

plt.tight_layout(pad=0.5, w_pad=0.5, h_pad=2.0)

20、图片输出方式

plt.savefig("fig.png")  # 输出方式1: 将图像存为一个png格式的图片文件
plt.show()              # 输出方式2: 在窗口中显示这幅图像

tight_layout在plt.savefig的调用方式相对比较稳定,我们将plt.show()函数替换为plt.savefig函数,替换后会在本地另外为png图片,该图片中子图填充了整个图像区域。 

plt.savefig('fig.png', bbox_inches='tight') # 替换 plt.show()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章