【问题标题】:How to automatically update the matplotlib graph and save it as PNG to a certain folder?如何自动更新matplotlib图并将其保存为PNG到某个文件夹?
【发布时间】:2020-03-12 13:59:18
【问题描述】:

我有一个代码可以生成一个覆盖/叠加甘特图,其中 x 轴为 time values,垂直红线代表 current time

在我当前的设置中,我的图表是从两个数据框(df 和 df1)生成的,其中一个(df1)将每隔一小时左右不断更新(另一个数据框全天保持静态,并且仅在结束)。我想将我的绘图保存在一个文件夹中,并希望它在预定的时间间隔内自动替换为更新的图表。为了清楚起见,我希望它更新/重绘图表并将文件夹中的旧 PNG 文件替换为较新的图表。

我知道有一个savefig 函数,但它只会保存我当前的情节一次,而不会替换旧的情节。我在网上搜索了一下,但找不到合适的解决方案。我什至不确定这是否可能。如果不是,我将不胜感激,如果您能建议一种替代解决方案来自动更新图表。

这是图表本身:Gantt Chart

这样做的主要目标是显示一天中取得的进展,并有或多或少的“实时”图表。我已经部署了一个应用程序,它从某个文件夹获取 PNG 文件并全屏显示,并在两个 URL(2 个网页)和分配的 PNG 文件夹之间交换“视图”。

这是我生成图表的代码的一部分。告诉我,我可以提供样本数据进行测试:

import pandas as pd
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import math
import time
import matplotlib.patches as mpatches
df = pd.read_csv('zpp00141_new.csv')
df1 = pd.read_csv('sample_data1.csv')
#convert times to number to calculate
def timestr_to_num(timestr):
    return mdates.date2num(datetime.strptime('0' + timestr if timestr[1] == ':' else timestr, '%I:%M:%S %p'))
#gantt chart plotting
fig, ax = plt.subplots(figsize=(12.5, 6))
operations = pd.unique(df['Operation/Activity'])
#Declaring a colormap
cmap = plt.cm.get_cmap('plasma_r')
colors = [cmap(i/20) for i in range(20)]
#plot scheduled operations 
for operation, color in zip(operations, colors):
    for row in df[df['Operation/Activity'] == operation].itertuples():
        left = timestr_to_num(row.start)
        right = timestr_to_num(row.finish)
        ax.barh(operation, left=left, width=right - left, height=1, color="#6ED06F", edgecolor = 'black', label = operation)
#plot "Actual" operations' times     
operations1 = pd.unique(df1['Operation/Activity'])
for operation, color in zip(operations1, colors):
    for row in df1[df1['Operation/Activity'] == operation].itertuples():
        left = timestr_to_num(row.start)
        right = timestr_to_num(row.finish)
        ax.barh(operation, left=left, width=right - left, height=0.4, color='#33AFFF', edgecolor = 'black', label = operation)
        #plt.legend()
#set x-axis limit
ax.set_xlim(timestr_to_num('06:00:00 AM'), timestr_to_num('4:30:00 PM'))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # display ticks as hours and minutes
ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # set a tick every hour
#set y and x labels
ax.set_xlabel('Time', fontsize = 'large')
ax.set_ylabel('Operation', fontsize = 'large')
plt.tight_layout()
ax.set_yticklabels(list(df['Operation/Activity'] + " - " + df['Operation short text'].astype(str)))
ax.tick_params(axis='both', which='major', labelsize=11)
#add a title to a plot
plt.title("Schedule", fontsize = 'x-large')
#convert "now" time to a certain format of hours:minutes:seconds am/pm and plot a vertical red line for the "Current time"
now = datetime.now()
now = now.strftime('%I:%M:%S %p')
plt.axvline(x=timestr_to_num(now),color='r', animated = True)
#adding the legend
patch = mpatches.Patch(color='#33AFFF', label='Actual')
patch2 = mpatches.Patch(color='#6ED06F', label='Planned')
plt.legend(handles=[patch, patch2], loc='upper left', fontsize = 'large')
#plt.legend(handles=[patch2], loc='upper left', fontsize = 'x-large')
plt.show()

【问题讨论】:

  • fig.savefig('path/to/folder/chart.png') 将在您每次运行脚本时用新图表替换旧图表。您是如何保存图表的?
  • @JuanJavierSantosOchoa 我使用的是简单的fig.savefig('plot_test1.png, bbpx_inches='tight'),我希望我的图表在没有我交互的情况下自动保存。我想我确实需要按照艾默生的建议在我的代码中添加另一个“类似循环”的模块。不过还是非常感谢您的建议!

标签: python pandas matplotlib automation


【解决方案1】:

您所展示的这个脚本将创建一个图表。 您现在需要的是要创建的模块中的另一层,它将定期运行,管理文件系统,将此图的输出打印到图像文件,然后更新必要的文件。

如果您运行的操作系统是 Linux,您可以设置一个 linux Cron 作业来自动运行您的映像更新功能。您还将受益于制作一个简单的 Bash 脚本,该脚本可以设置您的虚拟环境,然后运行该脚本。

除了那些 Linux 功能之外,您还需要探索 Pathlib 的基本教程。这个内置的 python 库将允许您读取文件系统,并对文件进行更改。

然后绘制PNG文件,参考this existing Stack question

【讨论】:

  • 感谢您的回复,不幸的是,我使用的是 Windows 10,由于公司的 IT 政策,我无法设置 Linux。我一定会检查 Pathlib。至于模块中的其他层,也许您可​​以简要说明我应该在模块中实现什么,或者写一个伪代码?我对 Python 很陌生,非常感谢任何帮助。
  • 我了解 IT 限制。 Cron 只是一种计划命令,Windows 10 应该有一个等效的程序。 Here is an existing discussion on the matter 我想你如何设置这个脚本是这样的: - 检查并设置任何丢失的目录 - 在临时目录中运行你的 .png 文件生成器 - 一旦成功生成 .PNG,将以前的 .PNG 文件移动到存档文件中名称中带有日期 - 将全新的 .PNG 文件移动到主目录 - 程序完成。
猜你喜欢
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多