python - 有什么方法可以在for循环中保存多个绘图而不用Python覆盖?

标签 python for-loop matplotlib

我有一个汇总数据框列表,其中包含不同国家的贸易统计数据。我可以通过循环遍历这个数据框列表来制作相应的图。现在我打算将它们保存在本地而不覆盖,我的意思是用各自的标题名称保存每个图。为此,我尝试了以下方法:

我有具有以下名称的数据框列表:

[dfList[i].name for i in range(len(dfList))]

['AR  fresh-Beef-E',
 'AUC  fresh-Beef-E',
 'BR  fresh-Beef-E',
 'CA  fresh-Beef-E',
 'CL  fresh-Beef-E',
 'CN  fresh-Beef-E',
 'E28  fresh-Beef-E',
 'EG  fresh-Beef-E',
 'IN  fresh-Beef-E',
 'JP  fresh-Beef-E',
 'KR  fresh-Beef-E',
 'MX  fresh-Beef-E',
 'NZ  fresh-Beef-E',
 'PY  fresh-Beef-E',
 'US  fresh-Beef-E',
 'UY  fresh-Beef-E',
 'ZA  fresh-Beef-E']

当前尝试:

打算将图形保存在本地,并将其绘图标题作为文件名:

import os
import pandas as pd
import matplotlib.pyplot as plt

outpath = r'C:/Users/plots'

if os.path.exists(outpath):
    shutil.rmtree(outpath)
_ = os.mkdir(outpath)

for i in range(len(dfList)) :
    plt.figure()
    my_plotter(dfList[i],title=dfList[i].name)
    plt.savefig(path.join(outpath,"dataname_{0}.png".format(i)))
    plt.close()

新更新

这是我的绘图函数的样子:

def my_plotter(df, plot_type='something', ylab_nm='something', title=None):
    fig, ax1 = plt.subplots(figsize=figsize)
    if plot_type=='something':
        _ = df.plot(kind='line', ax=ax1, marker='o', ls='-', linewidth=2, color=colors)
    else:
        df.loc[:, 'Total'] = df.sum(axis=1)
        _ = df.div(df.Total, axis=0).iloc[:, :-1].plot(kind='line', ax=ax1, marker='o', ls='--', linewidth=4, color=colors)
        df.drop('Total', axis=1, inplace=True)
        ax1.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=0))
        ax1.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1, interval=3))

    ax1.set(title=title)
    plt.title(title)
    ax1.xaxis.label.set_visible(False)
    plt.style.use('ggplot')
    plt.xticks(rotation=90)
    plt.show()

但是上述尝试没有将绘图保存到本地目录。我研究了 SO 并尝试了可能的建议,但我仍然没有得到所有应该通过其绘图标题命名并保存到本地文件目录的绘图。在我的尝试中,没有任何绘图被保存到本地目录中。

谁能告诉我如何完成这项工作?任何想法? 目标

我打算通过将每个图的标题作为文件名来保存它,并将其保存到本地目录。有什么想法吗?谢谢

最佳答案

这不是一个完整的 MWE,但我认为下面的修复应该可以帮助您。

import matplotlib.pyplot as plt
import pandas as pd
import os

# Only need to set the style once (not in loop)
plt.style.use('ggplot')

outpath = r'C:/Users/plots'

def my_plotter(df, plot_type='something', ylab_nm='something', title=None):
    fig, ax1 = plt.subplots(1, 1)
    if plot_type=='something':
        # Plots on ax1, so don't save output as another ax instance
        df.plot(kind='line', ax=ax1, marker='o', ls='-', linewidth=2)
    else:
        df.loc[:, 'Total'] = df.sum(axis=1)
        # Plots on ax1, so don't save output as another ax instance
        df.div(df.Total, axis=0).iloc[:, :-1].plot(kind='line', ax=ax1, marker='o', ls='--', linewidth=4, color=colors)
        df.drop('Total', axis=1, inplace=True)
        ax1.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=0))
        ax1.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1, interval=3))

    ax1.set(title=title)
    ax1.set_title(title, size=24, verticalalignment='bottom') 
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
    ax1.xaxis.label.set_visible(False)

    plt.xticks(rotation=90)
    plt.show()
    return fig, ax1

if os.path.exists(outpath):
    shutil.rmtree(outpath)
_ = os.mkdir(outpath)

for i in range(len(dfList)):
    fig, ax1 = my_plotter(dfList[i], title=dfList[i].name)
    fig.savefig(path.join(outpath,"dataname_{}.png".format(dfList[i].name)))
    plt.close()

关于python - 有什么方法可以在for循环中保存多个绘图而不用Python覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60303845/

相关文章:

python - 如何使用 PyOpengl 或 pyglet 在桌面上绘制?

jquery - 我如何在 django 中编写自己的自定义表单小部件

for-loop - Go 中的惯用拼接

excel - VBA打印指定单元格中数组的内容,然后跳出循环

python - matplotlib 说它需要 libpng15,但我有 libpng16

python - 如何增加Windows上气球弹出通知的时间

python - 测试 children 标签是否存在于 beautifulsoup 中

r - 如何在 R 中的列表列表上应用函数?

python - matplotlib 使用什么 GUI 库?

python - 如何从图像中提取 RGB 并仅将 RG 绘制为图形? R代表X,G代表Y