【问题标题】:Matplotlib way to annotate bar plots with lines and figures [duplicate]Matplotlib用线条和图形注释条形图的方法[重复]
【发布时间】:2017-10-18 09:36:43
【问题描述】:

我想为条形图创建一个注释,将条形图的值与两个参考值进行比较。如图所示的叠加,一种工作人员仪表,是可能的,但我愿意接受更优雅的解决方案。

条形图是使用matplotlibpandas API 生成的(例如data.plot(kind="bar")),所以如果解决方案能很好地使用它,那就更好了。

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:

    您可以为目标和基准指标使用较小的条形。 Pandas 无法自动注释条形图,但您可以简单地循环这些值并使用 matplotlib 的 pyplot.annotate 代替。

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    a = np.random.randint(5,15, size=5)
    t = (a+np.random.normal(size=len(a))*2).round(2)
    b = (a+np.random.normal(size=len(a))*2).round(2)
    df = pd.DataFrame({"a":a, "t":t, "b":b})
    
    fig, ax = plt.subplots()
    
    
    df["a"].plot(kind='bar', ax=ax, legend=True)
    df["b"].plot(kind='bar', position=0., width=0.1, color="lightblue",legend=True, ax=ax)
    df["t"].plot(kind='bar', position=1., width=0.1, color="purple", legend=True, ax=ax)
    
    for i, rows in df.iterrows():
        plt.annotate(rows["a"], xy=(i, rows["a"]), rotation=0, color="C0")
        plt.annotate(rows["b"], xy=(i+0.1, rows["b"]), color="lightblue", rotation=+20, ha="left")
        plt.annotate(rows["t"], xy=(i-0.1, rows["t"]), color="purple", rotation=-20, ha="right")
    
    ax.set_xlim(-1,len(df))
    plt.show()
    

    【讨论】:

      【解决方案2】:

      没有直接的方法来注释条形图(据我所知) 前段时间我需要注释一个,所以我写了这个,也许你可以根据你的需要调整它。

      import matplotlib.pyplot as plt
      import numpy as np
      
      ax = plt.subplot(111)
      ax.set_xlim(-0.2, 3.2)
      ax.grid(b=True, which='major', color='k', linestyle=':', lw=.5, zorder=1)
      # x,y data
      x = np.arange(4)
      y = np.array([5, 12, 3, 7])
      # Define upper y limit leaving space for the text above the bars.
      up = max(y) * .03
      ax.set_ylim(0, max(y) + 3 * up)
      ax.bar(x, y, align='center', width=0.2, color='g', zorder=4)
      # Add text to bars
      for xi, yi, l in zip(*[x, y, list(map(str, y))]):
          ax.text(xi - len(l) * .02, yi + up, l,
                  bbox=dict(facecolor='w', edgecolor='w', alpha=.5))
      ax.set_xticks(x)
      ax.set_xticklabels(['text1', 'text2', 'text3', 'text4'])
      ax.tick_params(axis='x', which='major', labelsize=12)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2016-10-13
        • 1970-01-01
        • 2014-06-28
        • 2014-12-15
        • 2015-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多