如何在matplot/python中绘制这样的图?

2024-04-26 01:04:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本这样的字典,想把某个流媒体的在线时间形象化。你知道吗

{1: ['2018-09-20 20:40:50', '2018-09-20 21:11:14'], 2: ['2018-09-20 12:45:44', '2018-09-20 13:22:24']}

我画了张花哨的图给你看我需要什么样的图表。你知道吗

diagram

因为我对python完全是初学者,所以我不知道如何用matplot来绘制这个。任何帮助都将不胜感激。你知道吗


Tags: 字典图表时间绘制流媒体初学者花哨matplot
3条回答

Plotly如果您不局限于Matplotlib,那么它有现成的交互式甘特图。你知道吗

import plotly.plotly as py
import plotly.figure_factory as ff

df = [dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
      dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'),
      dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30')]

fig = ff.create_gantt(df)
py.iplot(fig, filename='gantt-simple-gantt-chart', world_readable=True)

Output

下面是一个例子。甘特图的诀窍是计算原点和所需时间之间的偏移量。请参阅下面的代码和一些注释。你知道吗

import datetime
from matplotlib import pyplot as plt
data = {1: ['2018-09-20 20:40:50', '2018-09-20 21:11:14'], \
 2: ['2018-09-20 12:45:44', '2018-09-20 13:22:24']}

fig, ax = plt.subplots() # open figure; create axis
ylabels = [] # extract the dates
yticks  = [] # track the position on the y-axis
for k, v in data.items():
    # extract the time > see python docs for meaning of the symbols
    times = [datetime.datetime.strptime(i, '%Y-%m-%d %H:%M:%S') for i in v] 
    offset= times[0].hour # offset from the left
    delta = times[1].hour - times[0].hour # compute stream time
    ax.barh(k, delta, left = offset, align = 'center') # plot
    ylabels.append(v[0].split(' ')[0]) # extract date
    yticks.append(k)
# format figure
ax.set(**dict(xlabel = 'Time[hour]', xlim = (0, 24), \
              yticks = yticks, yticklabels = ylabels))
fig.show()

enter image description here

你想画的似乎是甘特图。 您可以看到一个关于在this link上使用matplot绘制甘特图的好例子

相关问题 更多 >