【问题标题】:Matplotlib multiple figures opening and savingMatplotlib 多图打开和保存
【发布时间】:2018-08-08 18:03:12
【问题描述】:

您好,我在从 pandas 数据框中绘制数据时遇到问题。在几个 for 循环中,我想创建一个大散点图(multiplots.png),在每个循环中添加新数据,同时还创建单独的图,在每个 j 循环中绘制和保存(plot_i_j.png)。

在我的代码中, plots_i_j.png 图形是正确生成的,但 multiplots.png 总是最终成为最后一个 plot_i_j.png 图形。如您所见,我试图在 axComb 上绘制 multiplots.png,而 plot_i_j.png 数字绘制在 ax 上。谁能帮我解决这个问题?

import pandas as pd
import matplotlib.pyplot as plt

columnNames = ['a','b']
scatterColors = ['red','blue','green','black']

figComb, axComb = plt.subplots(figsize=(8,6))

for i in range(4): # this is turbine number
    df1 = pd.DataFrame(np.random.randn(5, 2), columns=columnNames)
    df2 = pd.DataFrame(np.random.randn(5, 2), columns=columnNames)
    print(df1)
    for j in range(2):
        fig, ax = plt.subplots(figsize=(8,6))
        fig.suptitle(str(i)+'_'+str(j), fontsize=16)
        df1.plot(columnNames[j], ax=ax, color='blue', ls="--")
        plt.savefig('plot_'+str(i)+'_'+str(j)+'.png')
        df1.reset_index().plot.scatter('index',columnNames[j],3,ax=axComb,color=scatterColors[j])
        df2.reset_index().plot.scatter('index',columnNames[j],100,ax=axComb,color=scatterColors[j])   
plt.savefig('multiPlots.png')

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

真是一个小错误。当您执行plt.savefig 时,matplotlib 会查找最后调用的图形。

plt.savefig('plot_'+str(i)+'_'+str(j)+'.png') 替换为fig.savefig('plot_'+str(i)+'_'+str(j)+'.png')

并将plt.savefig('multiPlots.png') 替换为figComb.savefig('multiPlots.png')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多