首页 > 解决方案 > 在 Python 中绘制多个幂函数

问题描述

我正在尝试在 python 中绘制三个幂函数,但出现值错误。这是我的代码。我该如何解决?请帮忙

代码:

from numpy import *
import math
import matplotlib.pyplot as plt

a = logspace(-4, 2, 10)

m = 0.315*a**-3
r = 0.0000926*a**-2
d = 0.685

plt.plot(a, m, 'r') 
plt.plot(a, r, 'b') 
plt.plot(a, d, 'g') 
plt.show()

错误信息:

 ValueError: x and y must have same first dimension, but have shapes (10,) and (1,)

标签: matplotlib

解决方案


正如 JohanC 建议的那样,您需要相同数量的元素ad变量。如果有帮助,我只是使用他的建议并为您绘制图表。

import numpy as np
import matplotlib.pyplot as plt

a = np.logspace(-4, 2, 10)

m = 0.315*a**-3
r = 0.0000926*a**-2
d = 0.685

fig = plt.figure(figsize=(4, 3), dpi=200)
plt.plot(a, m, 'r', label='a v/s m') 
plt.plot(a, r, 'b', label='a v/s r') 
# plt.plot(a, d, 'g') # As JohanC suggested you need same number of elements for a and d variable
plt.plot(a, np.full_like(a, d), 'g', label='a v/s d') # alternatively use this
plt.yscale('log')
plt.grid()
plt.legend()

在此处输入图像描述


推荐阅读