【问题标题】:Plotting a Bar Chart on matplotlib在 matplotlib 上绘制条形图
【发布时间】:2020-02-28 21:50:04
【问题描述】:

如何绘制水平条形图,其值位于条形末尾,类似于this

我试过了

plt.barh(inc.index,inc)
plt.yticks(inc.index)
plt.xticks(inc);
plt.xlabel("Order Count")
plt.ylabel("Date")

Bar chart

【问题讨论】:

标签: python matplotlib


【解决方案1】:

答案可以在这里找到: How to display the value of the bar on each bar with pyplot.barh()?

就像 cphlewis 所说的那样添加 for 循环:

for i, v in enumerate(inc):
    ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')
plt.show()

这是我针对您的情况尝试的代码:

import matplotlib.pyplot as plt
import numpy as np
inc = [12, 25, 50, 65, 40, 45]
index = ["2019-10-31", "2019-10-30", "2019-10-29", "2019-10-28", "2019-10-27", "2019-10-26"]

fig, ax = plt.subplots()
ax.barh(index,inc, color='black')
plt.yticks(index)
plt.xticks(inc);
plt.xlabel("Order Count")
plt.ylabel("Date")

# Set xticks
plt.xticks(np.arange(0, max(inc)+15, step=10))

# Loop for showing inc numbers in the end of bar
for i, v in enumerate(inc):
    ax.text(v + 1, i, str(v), color='black', fontweight='bold')
plt.show()

剧情如下:

【讨论】:

【解决方案2】:

要生成叠加值的图,请运行:

ax = inc.plot.barh(xticks=inc, xlim=(0, 40));
ax.set_xlabel('Order Count')
ax.set_ylabel('Date')
for p in ax.patches:
    w = p.get_width()
    ax.annotate(f' {w}', (w + 0.1, p.get_y() + 0.1))

请注意,我将 xlim 的上限设置为略高于 最大Order Count,为注释提供空间。

对于我得到的你的数据子集:

还有一项改进:

如我所见,您的数据是一个 Series,带有 DatetimeIndex

因此,如果您希望将 y 标签值作为日期(没有 00:00:00 小时),将索引转换为字符串

inc.index = inc.index.strftime('%Y-%m-%d')

像我一样,生成我的情节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2022-08-06
    • 2017-06-30
    • 1970-01-01
    • 2018-03-10
    • 2018-11-26
    相关资源
    最近更新 更多