mid*_*idi 5 python data-visualization matplotlib pandas data-science
跟进我之前的问题:按小时将日期时间对象排序到 pandas 数据框,然后可视化为直方图
我需要为代表观看者计数的一个 X 轴值绘制 3 个条形图。现在他们显示一分钟以内或以上的内容。我需要一个向全体观众展示的内容。我有数据框,但我似乎无法让它们看起来正确。只要有 2 个栏,我就没有问题,看起来就像我想要有两个栏:
代码的相关部分:
# 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]
Run Code Online (Sandbox Code Playgroud)
我用来表示 X 轴的小时变量可能有问题,因为我将其转换为字符串,这样我就可以使小时看起来像而不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')
Run Code Online (Sandbox Code Playgroud)
现在我设置了align='edge'
,两个宽度值是绝对值和负值。但我不知道如何让它看起来正确的 3 条。我没有找到任何关于酒吧的定位参数。我也尝试使用 plt.hist() 但无法获得与 plt.bar() 函数相同的输出。
因此,我希望在左侧上方显示的图表上有第三个条形图,比其他两个条形图稍宽一些。
pandas
如果您一步而不是两步(或三步)绘制条形图,它将为您完成此对齐。考虑这个例子(改编自文档,为每只动物添加第三个栏)。
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()
Run Code Online (Sandbox Code Playgroud)
在纯 matplotlib 中,您可以调整绘图的 x 值,而不是像您所做的那样使用宽度参数来定位条形:
import numpy as np
import matplotlib.pyplot as plt
# Make some fake data:
n_series = 3
n_observations = 5
x = np.arange(n_observations)
data = np.random.random((n_observations,n_series))
# Plotting:
fig, ax = plt.subplots(figsize=(20,5))
# Determine bar widths
width_cluster = 0.7
width_bar = width_cluster/n_series
for n in range(n_series):
x_positions = x+(width_bar*n)-width_cluster/2
ax.bar(x_positions, data[:,n], width_bar, align='edge')
Run Code Online (Sandbox Code Playgroud)
在您的特定情况下,seaborn可能是一个不错的选择。您应该(几乎总是)尝试将数据保留为长格式,因此最好保留单个数据框并添加一列将每行标记为短,而不是三个单独的短、中和长数据框,中或长。使用这个新列作为hue
Seaborn 中的参数barplot
归档时间: |
|
查看次数: |
16161 次 |
最近记录: |