【问题标题】:Plot multiple csv files with 1 plot function使用 1 个绘图功能绘制多个 csv 文件
【发布时间】:2020-04-03 17:49:15
【问题描述】:

我有 4 个不同的 csv 文件(从 1 个 xlsm 工作簿中提取)。我的绘图功能有点复杂,但每个文件在其中一个文件上都非常完美。如果我尝试用循环绘制所有 4 个文件,我总是会得到一个

ValueError:数组的长度必须相同

然后该函数正在绘制列表中的第一个元素。我想为 csv 列表中的每个文件绘制相同的 plt.figure 和子图。我认为脚本试图在一个绘图上绘制所有不同的 csv 文件(csv 文件具有相同的结构但行数不同)

def plotMSN(data):  

    csv = data  
    #csv = "LL.csv" (this is working perfect)
    day = plotday
    ....

#this is not working
csvlist = ["LL.csv","UL.csv","UR.csv","LR.csv"]

for i in csvlist:
    plotMSN(i)
    time.sleep(5)

【问题讨论】:

    标签: python matplotlib plot data-science spyder


    【解决方案1】:

    如果您不设置子图,它们将全部绘制在同一个图上。有不止一种方法可以做到这一点,但我通常使用的是 fig,axis_array

    import matplotlib.pyplot as plt
    
    def plotMSN(i):
        #whatever you're doing in here
        ax.plot() #plot it on its own axis, this will reference the one you're on in your loop
    
    
    fig, axis_array = plt.subplots(len(csvlist), 1, subplot_kw = {'aspect':1}) #this will set up subplots that are arranged vertically
    for i, ax in zip(csvlist, axis_array):
        plotMSN(i)
    

    预计到达时间:

    OP 显然想绘制每个文件并使用该函数。为此,OP 需要修改:

    def plotMSN(i):
      #determine an appropriate name either in this function or in the loop that calls it 
      #plotting stuff here
      fig.savefig(new_filename)
      plt.close() # this prevents it from using the same instance over and over. 
    

    【讨论】:

    • 我的绘图函数很安静,现在很难全部重写。我不能把这个绘图函数放在一个额外的脚本文件中,并在每个循环的不同 csv 文件上调用它吗?我不需要情节作为子情节,只需要每个作为 pdf 文件。
    • 看,我被你的问题中的“subplot”抛出了。如果您想要每个文件一个绘图文件,请将其保存在函数中,然后 plt.close()。
    猜你喜欢
    • 2017-07-20
    • 1970-01-01
    • 2017-07-14
    • 2020-06-21
    • 1970-01-01
    • 2020-12-05
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多