我对 matplotlib 和 python 有一点问题。所以我的问题是这条线没有出现在情节中。我正在尝试制作自定义函数的图表。我的代码如下:
fig, ax = plt.subplots(figsize=(8,4)) # Define the x axis values: x = np.linspace(2000,32000) # Creating the functions that we will plot def pmgc(x): return 0.853 def pmec(x): return (-124.84/(x)) + pmgc(x) for x in range(2000,32000): pmgc(x) pmec(x) #Plotting ax.plot(x,pmgc(x), color = 'blue',linewidth = 3) ax.plot(x,pmec(x), color = 'red',linewidth = 3) plt.rcParams["figure.autolayout"] = True ax.set_xlabel("Renda") plt.legend(labels = ['Propensão Marginal a Cosumir','Propensão Média a Cosumir'],loc = 'upper left', borderaxespad = 0,bbox_to_anchor=(1.02, 1)) plt.title('Gráfico da Questão 6, item c\nFeito por Luiz Mario. Fonte: Autor', loc='center')
每次我运行代码时,图表都会出现,没有线条。请问有人可以帮助我吗?谢谢你的关注:)
一些东西。您正在定义x,np.linspace(2000,32000)而是在您的 for 循环中使用另一个变量(例如 i)。然后,您想为您的 pmgc 和 pmec 值创建空列表以附加到您的 for 循环中。最后,你不想做for x in range(2000,32000):你想做的事情for i in np.linspace(2000, 32000):来匹配你的 x 列表的长度。np.linspace(2000, 32000)但是当你设置x为等于它时,你已经在上面的代码中定义了它。所以就做吧for i in x:。把它们放在一起,你就会得到你的台词:
x
np.linspace(2000,32000)
for x in range(2000,32000):
for i in np.linspace(2000, 32000):
np.linspace(2000, 32000)
for i in x:
fig, ax = plt.subplots(figsize=(8,4)) # Define the x axis values: x = np.linspace(2000,32000) # Creating the functions that we will plot def pmgc(x): return 0.853 def pmec(x): return (-124.84/(x)) + pmgc(x) pmgc_list = [] pmec_list = [] for i in x: pmgc_list.append(pmgc(i)) pmec_list.append(pmec(i)) #Plotting ax.plot(x,pmgc_list, color = 'blue',linewidth = 3) ax.plot(x,pmec_list, color = 'red',linewidth = 3) plt.rcParams["figure.autolayout"] = True ax.set_xlabel("Renda") plt.legend(labels = ['Propensão Marginal a Cosumir','Propensão Média a Cosumir'],loc = 'upper left', borderaxespad = 0,bbox_to_anchor=(1.02, 1)) plt.title('Gráfico da Questão 6, item c\nFeito por Luiz Mario. Fonte: Autor', loc='center')
输出: