【问题标题】:Timeline bar using matplotlib & PolyCollection - Python使用 matplotlib 和 PolyCollection 的时间线栏 - Python
【发布时间】:2020-07-16 03:16:36
【问题描述】:

我一直在尝试复制@theimportanceofbeingernest 对Timeline bar graph using python and matplotlib 的回答 并且似乎无法获得正确的输出图。

Here is my current output

Here is my desired output(但使用我的数据等)

我正在努力找出问题所在。 任何帮助将不胜感激! 谢谢。

代码如下:

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.collections import PolyCollection

data = [(dt.datetime(1900, 1, 1, 14, 19, 26), dt.datetime(1900, 1, 1, 14, 19, 29), 'index'),
        (dt.datetime(1900, 1, 1, 14, 19, 29), dt.datetime(1900, 1, 1, 14, 19, 31), 'links'),
        (dt.datetime(1900, 1, 1, 14, 19, 31), dt.datetime(1900, 1, 1, 14, 19, 33), 'guides'),
        (dt.datetime(1900, 1, 1, 14, 19, 33), dt.datetime(1900, 1, 1, 14, 19, 35), 'prices'),
        (dt.datetime(1900, 1, 1, 14, 19, 35), dt.datetime(1900, 1, 1, 16, 39, 47), 'index'),
        (dt.datetime(1900, 1, 1, 16, 39, 47), dt.datetime(1900, 1, 1, 16, 39, 48), 'prices')]

cats = {'index': 1, 'links': 2, 'guides': 3, 'prices': 4}
colormapping  = {'index': 'C0', 'links': 'C1', 'guides': 'C2', 'prices': 'C3'} 

verts = []
colors = []
for d in data:
    v =  [(mdates.date2num(d[0]), cats[d[2]]-.4),
          (mdates.date2num(d[0]), cats[d[2]]+.4),
          (mdates.date2num(d[1]), cats[d[2]]+.4),
          (mdates.date2num(d[1]), cats[d[2]]-.4),
          (mdates.date2num(d[0]), cats[d[2]]-.4)]
    verts.append(v)
    colors.append(colormapping[d[2]])

bars = PolyCollection(verts, facecolors=colors)

fig, ax = plt.subplots()
ax.add_collection(bars)
ax.autoscale()
loc = mdates.MinuteLocator(byminute=[0,30])
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(loc))

ax.set_yticks([1,2,3,4])
ax.set_yticklabels(['index', 'links', 'guides', 'prices'])
plt.show()

【问题讨论】:

    标签: python matplotlib visualization timeline


    【解决方案1】:

    你们的时差非常短。它们是几秒钟,而您的 x 范围是几小时。所以,这些条基本上是不可见的。

    请注意,在 matplotlib 中,区域通常在绘制时没有抗锯齿,这在将多个半透明区域放在一起时很有用。但是,线条以一定的粗细(在屏幕空间中)绘制并消除锯齿。因此,设置明确的边缘颜色有助于可视化这些“条”。

    bars = PolyCollection(verts, facecolors=colors, edgecolors=colors)
    

    【讨论】:

    • 当然!感谢您的帮助 - 这解决了我的问题!希望你有一个美好的一天先生:)
    猜你喜欢
    • 1970-01-01
    • 2019-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2019-02-13
    • 1970-01-01
    • 2021-01-03
    相关资源
    最近更新 更多