首页 > 解决方案 > 如何使用 matplotlib 在 Python 中绘制 f(x) = e^x - 4x^3 + 1?

问题描述

这是我用来用 matplotlib 绘制这个函数的代码:

import math
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2,2,1000)
fx = []
for i in range (len(x)):
    fx.append(math.exp(x[i]) - 4*x[i]**3 + 1)
    # print(math.exp(x[i]) - 4*x[i]**3 + 1)
plt.plot(x, fx)
plt.grid()
plt.axvline()
plt.axhline()
plt.show()

以下显示了我的代码在预期图表旁边的结果: 图 1 是我的代码结果,另一个是实际图表

标签: pythonmatplotlib

解决方案


似乎它的绘制是正确的,只是你得到的图和图像中的图形在不同的比例上。您可以尝试将比例因子乘以 5 以获得与图像相似的结果。

multiplier = 5

xmin, xmax = plt.xlim()
ymin, ymax = plt.ylim()

plt.xlim(xmin * multiplier, xmax * multiplier)
plt.ylim(ymin * multiplier, ymax * multiplier)

推荐阅读