总结用matplotlib画图遇到的一些问题
1. 导入包创建图
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
fig = plt.figure()
plt.plot([1, 2, 3, 8], [1, 3, 7, 9], marker='^', mec='r', mfc='r')
plt.show()
2. 设置汉字
如果图的标题、轴标签、刻度等需要汉字,直接画图汉字会乱码,在程序开头添加以下两行代码即可。
mpl.rcParams['font.sans-serif'] = [u'SimHei'] # 中文字体可修改
mpl.rcParams['axes.unicode_minus'] = False
设置图中中文标题
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
fig = plt.figure()
plt.title("中文标题")
plt.plot([1, 2, 3, 8], [1, 3, 7, 9], marker='^', mec='r', mfc='r')
plt.show()
3. 设置轴标签
plt.xlabel("x轴标签")
plt.ylabel("y轴标签")
添加轴标签并重新绘制:
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
fig = plt.figure()
plt.title("中文标题")
# 刻度也可用汉字
plt.plot(["刻度1", "刻度2", "刻度3", "刻度4"], [1, 3, 7, 9], marker='^', mec='r', mfc='r')
plt.xlabel('x轴轴标签')
plt.ylabel('y轴轴标签')
plt.show()
4. 刻度线内向
matplotlib画图时默认刻度线朝向外侧,如果需要刻度线内向,添加代码:
plt.rcParams['xtick.direction'] = 'in' # 刻度线内向
plt.rcParams['ytick.direction'] = 'in'
重新绘制
fig = plt.figure()
plt.rcParams['xtick.direction'] = 'in' # 刻度线内向
plt.rcParams['ytick.direction'] = 'in'
plt.plot([1, 2, 3, 8], [1, 3, 7, 9], marker='^', mec='r', mfc='r')
plt.show()
5. 添加图例
plt.plot(label='图例') # 图例名称
plt.legend()
实例展示:
fig = plt.figure()
plt.rcParams['xtick.direction'] = 'in' # 刻度线内向
plt.rcParams['ytick.direction'] = 'in'
plt.plot([1, 2, 3, 8], [1, 3, 7, 9], marker='^', mec='r', mfc='r', label='图例1')
plt.plot([2, 4, 6, 9], [2, 5, 8, 9], marker='s', mec='g', mfc='g', label='图例2')
plt.legend(loc='upper left')
plt.show()
持续更新…