我必须为列表中的每个项目绘制每个函数,而不是工作

时间:2017-12-01 02:34:14

标签: python plot graph

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure
xvals = np.linspace(0.4, 2, 100)    # generate x-values


def f1(xvals):
    return (1. / 3.) * (-1. + xvals**3)

def f2(xvals):
    return (1. / 2.) * (-1. + xvals**2)

def f3(xvals):
    return -1. + xvals

def f4(xvals):
    return 2.303*(np.log10(xvals))

def f5(xvals):
    return 1. - (1./xvals)

def f6(xvals):
    return (1. / 2) - (1. / (2.*xvals**2))

def f7(xvals):
    return (1. / 3.) - (1./(3.*xvals**3))


functions = [f1(xvals), f2(xvals), f3(xvals), f4(xvals), f5(xvals), f6(xvals), f7(xvals)]
plotters = [ plt.plot, plt.loglog, plt.semilogx, plt.semilogy ]


for plot in plotters:
    for func in functions:
        plot(xvals, func)

plt.xlabel("x"); plt.ylabel("f(x)") # add axis labels
myTitle = "Compare shapes of various functions of x through (1,1)"
plt.title(myTitle)                  # add plot title
plt.legend(loc = "lower right")     # add legend
plt.show()    

这应该为“绘图仪”中的每种绘图方法创建四个图形,它只创建1个图形,特别是绘图仪[1]和/或绘图仪[3](它们看起来相同)。它是我需要为学校做的实验室。我是新来的代码。控制台没有给我任何类型错误。

1 个答案:

答案 0 :(得分:0)

您需要创建子图。现在,你所有的情节都发生在一组轴上,所以每一个都覆盖了最后一个。

fig1 = plt.figure(figsize=(7, 10)) #you can set figure sizes too!!
#create axes for sub plots
ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
ax3 = plt.subplot(223)
ax4 = plt.subplot(224)

#actual plotting
for func in functions:
    ax1.plot(xvals, func)
    ax2.loglog(xvals, func)
    ax3.semilogx(xvals, func)
    ax4.semilogy(xvals, func)
# legends ( you don't have any)
for ax in [ax1, ax2, ax3, ax4]:
    ax.legend(loc="lower right")
#set titles for each axes
ax1.set_title('Regular plot')
ax2.set_title('Loglog plot')
ax3.set_title('Semilogx plot')
ax4.set_title('Semilogy plot')

plt.show()

这就是:enter image description here