【问题标题】:Show dashed line of mean for each bar plot显示每个条形图的均值虚线
【发布时间】:2019-08-21 21:30:59
【问题描述】:

我想绘制一条虚线,显示两个变量的平均值。这是我的条形图代码:

 import matplotlib
 import matplotlib.pyplot as plt
 import numpy as np

 men_means = [2000, 3400, 3000, 3005, 2700]
 women_means = [2500, 3200, 3004, 2000, 2005]

 x = np.arange(len(labels))  # the label locations
 width = 0.35  # the width of the bars

 fig, ax = plt.subplots()
 rects1 = ax.bar(x - width/2, men_means, width, label='Men')
 rects2 = ax.bar(x + width/2, women_means, width, label='Women')

这是我所期望的结果:

【问题讨论】:

  • 您希望您的线路是虚线而不是全连接吗?您图片中的线条确实与每个条形的平均值相交。
  • @CeliusStingher 一条虚线,我试过plot.axhline(np.mean(df), linestyle='--', color='blue'),但这适用于所有条形图。你能帮我吗,谢谢!!!
  • 不清楚你在问什么
  • 我将编辑您的问题,使其格式正确

标签: python matplotlib graph


【解决方案1】:

这里不涉及 Matplotlib 魔法;您只需要正确定义要绘制的内容。

您要绘制的线条是条形中心之间的连接。 条形的中心是通过将x 偏移width +/- 2 并将y 除以2 来计算的。

您可以使用简单的plt.plot 绘制这两行:

# Your code

plt.plot(
    x - width/2, 
    [y / 2 for y in men_means], 
    linestyle="--", 
    linewidth=3, 
    color="black"
)
plt.plot(
    x + width/2, 
    [y / 2 for y in women_means], 
    linestyle="--", 
    linewidth=3, 
    color="purple"
)

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    相关资源
    最近更新 更多