Last Updated: 2023-10-02 14:19:01 Monday
-- TOC --
本文示例代码,用matplotlib绘制基本数学函数图形,\(y=x^n\),展示几个使用matplotlib的小技巧。
示例代码:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 1000)
fig, ax = plt.subplots()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
ax.set_title(r'$y=x^n$')
ax.plot(x, x, 'r--', linewidth=1, label=r'$y=x$')
ax.plot(x, x**2, 'b:', linewidth=1, label=r'$y=x^2$')
ax.plot(x, x**3, 'g-.', linewidth=1, label=r'$y=x^3$')
ax.plot(x, x**4, linewidth=1, label=r'$y=x^4$')
ax.plot(x, x**5, linewidth=1, label=r'$y=x^5$')
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
ax.legend()
ax.set_xlabel('x', fontsize=12, color='red')
ax.set_ylabel('y')
ax.text(1, -2, r'$\alpha\beta$')
ax.grid(True)
plt.show()
效果图:
ax.spines
来控制坐标轴的位置ax.set_xlim
设置x轴的显示范围ax.text
在指定位置写入文字或公式,也可以设置fontsize和colorax.grid
控制是否显示网格,默认是Falseax.set_xlabel
同样支持fontsize和color设置刻度和label位置
示例代码:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 1000)
fig, ax = plt.subplots()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
ax.plot(x, np.sin(x), 'r--', linewidth=1)
ax.set_ylim(-1.5, 1.5)
ax.set_xticks([-2*np.pi,
-1.5*np.pi,
-np.pi,
-0.5*np.pi,
0,
0.5*np.pi,
np.pi,
1.5*np.pi,
2*np.pi])
ax.set_xticklabels([r'$-2\pi$',
r'$-\frac{3}{2}\pi$',
r'$-\pi$',
r'$-\frac{1}{2}\pi$',
r'$0$',
r'$\frac{1}{2}\pi$',
r'$\pi$',
r'$\frac{3}{2}\pi$',
r'$2\pi$'])
ax.set_xlabel('x', labelpad=0, x=0.55)
ax.set_ylabel('y=sin(x)', labelpad=0, y=0.75)
ax.grid(True)
plt.show()
效果图:
labelpad
表示label距离轴的垂直距离,设为0还是很大。x
和y
分表定位显示位置的刻度。本文链接:https://cs.pynote.net/sf/python/matplotlib/202309265/
-- EOF --
-- MORE --