用matplotlib绘制数学函数图形

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()

效果图:

math

设置刻度和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()

效果图:

ticks_label

本文链接:https://cs.pynote.net/sf/python/matplotlib/202309265/

-- EOF --

-- MORE --