【python】Matplotlib作图小结

Matplotlib tutorials: https://matplotlib.org/tutorials/index.html

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2, 100)

# Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
fig, ax = plt.subplots()  # Create a figure and an axes.
ax.plot(x, x, label='linear')  # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...
ax.plot(x, x**3, label='cubic')  # ... and some more.
ax.set_xlabel('x label')  # Add an x-label to the axes.
ax.set_ylabel('y label')  # Add a y-label to the axes.
ax.set_title("Simple Plot")  # Add a title to the axes.
ax.legend()  # Add a legend.
plt.show()

图示结果:

  • 调整图中字体的大小和格式
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2, 100)

fig, ax = plt.subplots()
ax.plot(x, x, label='linear')
ax.plot(x, x**2, label='quadratic')
ax.plot(x, x**3, label='cubic')

#设置坐标刻度值的大小以及刻度值的字体
plt.tick_params(labelsize=12)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]

# 设置横纵坐标的名称以及对应字体格式
font1 = {
    
    'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 14,
}
plt.xlabel("x label", font1)
plt.ylabel("y label", font1)


#设置图例并且设置图例的字体及大小
font2 = {
    
    'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 12,
}
ax.legend(loc='best', prop=font2)
plt.savefig('figure.png', dpi=300)
plt.show()

图示结果:
在这里插入图片描述

  • 科学计数法
`
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1, 100, 100)
fig, ax = plt.subplots(1, 1)
ax.plot(x, x**2)
ax.set(xlabel='x', ylabel='x^2',
       title='scientific notation')

# scientific notation
from matplotlib import ticker
formatter = ticker.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-1,1))
ax.yaxis.set_major_formatter(formatter) # for y axis
ax.xaxis.set_major_formatter(formatter) # for x axis

ax.grid()
fig.savefig("test.png", dpi=300)
plt.show()

图示结果:
在这里插入图片描述
其他参考:
CSDN博客《python matplotlib 画图刻度、图例等字体、字体大小、刻度密度、线条样式设置
CSDN博客《matplotlib命令与格式:图例legend语法及设置

猜你喜欢

转载自blog.csdn.net/yideqianfenzhiyi/article/details/100594651
今日推荐