【问题标题】:matplotlib advanced bar plotmatplotlib 高级条形图
【发布时间】:2013-11-23 22:01:42
【问题描述】:

我需要重新创建一个类似于下面在 Excel 中创建的图表。我希望使用 matplotlib,但似乎找不到任何示例或参考来说明如何制作这样的图表。我需要根据性能阈值对条形进行着色,并显示阈值。谁能指出我正确的方向?不过,我确实需要能够用 Python 做到这一点。

【问题讨论】:

标签: python graph matplotlib plot


【解决方案1】:

我得跑了,但这里有一些东西可以让你开始:

import numpy as np
import matplotlib
matplotlib.rcParams['text.usetex'] = False
import matplotlib.pyplot as plt
import pandas

df = pandas.DataFrame(np.random.uniform(size=37)*100, columns=['A'])
threshold = 75
fig, ax = plt.subplots(figsize=(8,3))

good = df['A'][df['A'] >= threshold]
bad = df['A'][df['A'] < threshold]

ax.bar(left=good.index, height=good, align='center', color='ForestGreen', zorder=5)
ax.bar(left=bad.index, height=bad, align='center', color='Firebrick', zorder=5)

ax.axhline(y=threshold, linewidth=2, color='ForestGreen', zorder=0)

ax.set_xticks(df.index)
ax.set_xlim(left=df.index[0]-0.75, right=df.index[-1]+0.75)

def annotateBars(row, ax=ax):
    if row['A'] < 20:
        color = 'black'
        vertalign = 'bottom'
        vertpad = 2
    else:
        color = 'white'
        vertalign = 'top'
        vertpad = -2

    ax.text(row.name, row['A'] + vertpad, "{:.1f}%".format(row['A']),
            zorder=10, rotation=90, color=color,
            horizontalalignment='center',
            verticalalignment=vertalign,
            fontsize=8, weight='heavy')

junk = df.apply(annotateBars, ax=ax, axis=1)

这给了我:

【讨论】:

    【解决方案2】:

    现在可以更简洁地绘制:

    1. Axes.bar_label 自动标记条形 (requires matplotlib 3.4.0+)
    2. Axes.bar 有一个 color 参数,可以接受一组颜色(例如,通过 numpy.where

    所以现在只需要几行,例如使用保罗的样本df = pd.DataFrame({'A': np.random.uniform(size=35) * 100})

    fig, ax = plt.subplots(figsize=(9, 3))
    threshold = 75
    
    # plot bars as blue if A > threshold, else red
    color = np.where(df.A > threshold, 'blue', 'red')
    ax.bar(x=df.index, height=df.A, color=color)
    
    # add bar labels
    ax.bar_label(ax.containers[0], fmt='%.1f%%')
    
    # add threshold line
    ax.axhline(threshold, alpha=0.5, zorder=0)
    

    或者对于多个阈值,只需根据需要更新color(例如通过numpy.select):

    upper, lower = 75, 25
    color = np.select([df.A > upper, df.A < lower], ['blue', 'red'], default='gray')
    

    请注意,颜色数组也可以传递给其他条形图助手:

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 1970-01-01
      • 2018-09-30
      • 2016-01-02
      • 2017-03-27
      • 2015-12-25
      • 2016-09-11
      • 1970-01-01
      相关资源
      最近更新 更多