文章目录
常规绘图
导入模块
import numpy as np
import matplotlib.pyplot as plt
中文显示设置
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# 有中文出现的情况,需要u'内容'
确定x,y值
x = np.arange(0, 300, 1)
y1 = np.random.rand(300, 1)
y2 = np.random.rand(300, 1)
设置图片标题(保存时,默认以该标题命名)
plt.figure(num = "图片名称")
绘制图形
lines = plt.plot(x, y1, 'bs--',
x, y2, 'rs--')
设置曲线属性(标题、图例、坐标轴名称)
plt.title(u'测试', fontproperties='SimHei') # 曲线名称
plt.legend((u'蓝色', '红色'), loc='best') # 图例
plt.xlabel(u'x坐标', fontproperties='SimHei') # x坐标轴名称
plt.ylabel(u'y坐标', fontproperties='SimHei') # y坐标轴名称
plt.grid() # 打开网格
坐标轴刻度的设置
设置坐标轴刻度范围
plt.xlim(x.min(), x.max())
plt.ylim(min(y1.min(), y2.min())*0.9, max(y1.max(), y2.max())*1.1)
plt.show()
坐标轴主次刻度的设置
需要的模块
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
设置
xmajorLocator = MultipleLocator(10) # x坐标轴主刻度
xminorLocator = MultipleLocator(1) # x坐标轴次刻度
ymajorLocator = MultipleLocator(0.01) # 将y轴主刻度标签设置为0.01的倍数
yminorLocator = MultipleLocator(0.001) # 将此y轴次刻度标签设置为0.001的倍数
ax = plt.gca()
ax.xaxis.set_major_locator(xmajorLocator)
ax.xaxis.set_minor_locator(xminorLocator)
ax.yaxis.set_major_locator(ymajorLocator)
ax.yaxis.set_minor_locator(yminorLocator)
ax.xaxis.grid(True, which='major') # 打开x轴主刻度网格
ax.yaxis.grid(True, which='major') # 打开y轴主刻度网格