【发布时间】: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