gpt4 book ai didi

python - 使用 ax.bar() 使用 matplotlib 绘制多个条形图

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:32 24 4
gpt4 key购买 nike

跟进我之前的问题:Sorting datetime objects by hour to a pandas dataframe then visualize to histogram

我需要为一个 X 轴值绘制 3 个条形图,表示观看者计数。现在他们展示了不到一分钟或更长的时间。我需要一个显示整体观众的。我有 Dataframe,但我似乎无法让它们看起来正确。只有 2 个条我没问题,看起来就像我想要两个条一样: I need to plot 3 bars for one X-axis value representing viewer counts.

代码的相关部分:

# Time and date stamp variables
allviews = int(df['time'].dt.hour.count())
date = str(df['date'][0].date())
hours = df_hist_short.index.tolist()
hours[:] = [str(x) + ':00' for x in hours]

我用来表示 X 轴的 hours 变量可能有问题,因为我将它转换为字符串,所以我可以使 hours 看起来像 23:00 而不仅仅是 pandas 索引输出23 等。我见过人们在 X 中添加或减去值以更改条形位置的示例。

fig, ax = plt.subplots(figsize=(20, 5))
short_viewers = ax.bar(hours, df_hist_short['time'], width=-0.35, align='edge')
long_viewers = ax.bar(hours, df_hist_long['time'], width=0.35, align='edge')

现在我设置了 align='edge' 并且两个宽度值是绝对值和负值。但我不知道如何用 3 条让它看起来正确。我没有找到酒吧的任何定位参数。我也曾尝试使用 plt.hist(),但无法获得与 plt.bar() 函数相同的输出。

因此,我希望在左侧上方显示的图表中有第三个条形图,比其他两个条形图宽一些。

最佳答案

pandas 会为您进行对齐,如果您一步而不是两步(或三步)绘制条形图。考虑这个例子(改编自 docs 为每只动物添加第三个栏)。

import pandas as pd
import matplotlib.pyplot as plt

speed = [0.1, 17.5, 40, 48, 52, 69, 88]
lifespan = [2, 8, 70, 1.5, 25, 12, 28]
height = [1, 5, 20, 3, 30, 6, 10]
index = ['snail', 'pig', 'elephant',
'rabbit', 'giraffe', 'coyote', 'horse']
df = pd.DataFrame({'speed': speed,
'lifespan': lifespan,
'height': height}, index=index)
ax = df.plot.bar(rot=0)

plt.show()

enter image description here

关于python - 使用 ax.bar() 使用 matplotlib 绘制多个条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56076590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com