Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

python - Matplot charts getting superimposed cumulatively in for loop of pandas data frames

My issue is when I run a for loop and try to save my charts, they superimpose onto the next cumulatively if I don't run the line plt.show(). I am making a pdf from the saved images so I do not need or want them to show. It runs perfect with plt.show(). I just have to manually close these plots for the program to continue.

enter image description here

enter image description here

I have the john hopkins covid data being read into pandas to create many different charts and this is the only plot I have issues with though most are quite similar. For my final plot it is reduced to single column sum of the total cases/deaths for use with bar charts. I stumbled onto merging two plot types, bar and area, which makes a cool effect. However, I am sure this is not the issue as I comment out one and still get the plots to display on top of each if i do not add plt.show()

def home_plots(start, end, home='Arizona'):
    for n, obj in enumerate(Covid.DFS[:2]):
        kind = obj.kind
        daily = obj.df
        daily = daily[daily['State'] == home]
        daily = daily.loc[:, start:end]
        daily_sum = daily.sum(axis=1).sort_values()  # ascending=False)

        capita = obj.pc
        capita = capita[capita['State'] == home]
        capita = capita.loc[:, start:end]
        capita_sum = capita.sum(axis=1).sort_values()  # ascending=False)

        c_map = cm.get_cmap('Oranges', len(daily) if len(daily) < 20 else 20)
        color_scale = [colors.rgb2hex(c_map(i)) for i in range(c_map.N)]

        # This will stack 2 plots with same instance. single values only
        for i, df in enumerate([daily_sum, capita_sum]):
            print(df)
            df.tail(20).T.plot(kind='area', stacked=False, color=color_scale[::-1], figsize=(14, 7))
            df.tail(20).T.plot(kind='bar', color=color_scale, rot=45, legend=False)
            plt.title(f"{home}:{kind}{' per capita 100,000' if i % 2 == 0 else ''}")
            plt.tight_layout(pad=5)
            plt.savefig(f'covid_charts/home_plot_chart{n}{i}', dpi=150)
            # plt.show()
question from:https://stackoverflow.com/questions/65944439/matplot-charts-getting-superimposed-cumulatively-in-for-loop-of-pandas-data-fram

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...