简体   繁体   English

如何创建 Y 轴不明确的堆叠条形图/猫图?

[英]How do I create stacked barplots / catplots with ambigious Y axis?

I have grouped and aggregated data with such columns.我已经使用这些列对数据进行了分组和聚合。 They are populated with median values.它们填充有中值。

name; online_days; offline_days; hybrid_days
foo; 1; 2; 0
bar; 0.5; 2.5; 0
test; 1.5; 1.5; 0

I need to plot something like this我需要绘制这样的图

例子

I tried sns.catplot but it requires specific Y axis, whether I want Y axis to be online_days , offline_days , hybrid_days我试过sns.catplot但它需要特定的 Y 轴,我是否希望 Y 轴为online_daysoffline_dayshybrid_days

Answer回答

You need to organize your data in a pandas.DataFrame , then you need to reshape this dataframe with pandas.melt in order to have a dataframe like this:您需要在pandas.DataFrame组织您的数据,然后您需要使用pandas.melt重塑此数据帧,以便获得这样的数据帧:

name      day type  median
 foo   online_days     1.0
 bar   online_days     0.5
test   online_days     1.5
 foo  offline_days     2.0
 bar  offline_days     2.5
test  offline_days     1.5
 foo   hybrid_days     0.0
 bar   hybrid_days     0.0
test   hybrid_days     0.0

Finally, you can plot your data throughseaborn.barplot() .最后,您可以通过seaborn.barplot()绘制数据。

Code代码

# import
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# data
df = pd.DataFrame({'name': ['foo', 'bar', 'test'],
                   'online_days': [1, 0.5, 1.5],
                   'offline_days': [2, 2.5, 1.5],
                   'hybrid_days': [0, 0, 0]})
df = pd.melt(frame = df,
             id_vars = 'name',
             var_name = 'day type',
             value_name = 'median')

# plotting
fig, ax = plt.subplots()

sns.barplot(ax = ax,
            data = df,
            x = 'name',
            y = 'median',
            hue = 'day type')

plt.show()

Output输出

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM