【问题标题】:Adding a line on top of each bar in MatPlotlib graph在 MatPlotlib 图中的每个条形顶部添加一条线
【发布时间】:2023-03-04 20:17:01
【问题描述】:

我有下图的代码。我需要为每个图表添加一个阈值。此值确实会从一组更改为另一组。

import numpy as np
import matplotlib.pyplot as plt

n_groups = 4
heuristic = (230.193, 33.96, 46, 8)
safe = (195.8, 24.83, 36, 7)

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.1
opacity = 0.8

rects1 = plt.bar(index, heuristic, bar_width,
             marker="D",
             alpha=opacity,
             color='b',
             label='Heuristic')

rects2 = plt.bar(index + bar_width, safe, bar_width,
             alpha=opacity,
             color='g',
             label='SAFE')

plt.xlabel('Firmware')
plt.ylabel('nDCG')
plt.title('Matching results by firmware')
plt.xticks(index + bar_width, ('Mqtt', 'Solder', 'Iron', 'Sympetrum'))
plt.legend()

plt.tight_layout()
plt.show()

以下是它生成的图表,我使用 粉色标记 向您展示了我希望代码生成的内容。对不起,线条不直。非常感谢任何帮助。谢谢

【问题讨论】:

    标签: python matplotlib graph


    【解决方案1】:

    这是一种使用hlines的方法:

    import numpy as np
    import matplotlib.pyplot as plt
    
    n_groups = 4
    heuristic = (230.193, 33.96, 46, 8)
    safe = (195.8, 24.83, 36, 7)
    threshold = (250, 50, 80, 30)
    
    # create plot
    fig, ax = plt.subplots()
    index = np.arange(n_groups)
    bar_width = 0.1
    opacity = 0.8
    
    rects1 = plt.bar(index, heuristic, bar_width,
                 #marker="D",
                 alpha=opacity,
                 color='b',
                 label='Heuristic')
    
    rects2 = plt.bar(index + bar_width, safe, bar_width,
                 alpha=opacity,
                 color='g',
                 label='SAFE')
    
    [
        ax.hlines(
            threshold[i],
            index[i] - bar_width / 2,
            index[i] + bar_width * 1.5,
            colors="deeppink",
        )
        for i in range(len(safe))
    ]
    
    plt.xlabel('Firmware')
    plt.ylabel('nDCG')
    plt.title('Matching results by firmware')
    plt.xticks(index + bar_width, ('Mqtt', 'Solder', 'Iron', 'Sympetrum'))
    plt.legend()
    
    plt.tight_layout()
    plt.show()
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-02
      • 2019-01-25
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多