数值在 python 中的分组条形图
Grouped bar graphs with numerical values in python
我无法分享我的数据集,但它看起来像这样。
类别
销售额
利润
(7种)
(浮动)
(浮动)
实际上有 6 列带有数值变量。我想在 python 上将其绘制为分组条形图,其中类别作为 x 轴,各个条形线表示数字列的平均值。 seaborn 的 catplot 中的 hue 参数只接受分类值,所以我不能使用它。
还有其他方法可以绘制吗?
Seaborn 更喜欢 "long form". You can use df.melt(id_vars='category')
中的数据来转换数据帧。
这是一个例子:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
sns.set()
df = pd.DataFrame({'category': np.random.choice([*'abcdefg'], 100),
'sales': np.random.randint(1000, 2000, 100),
'profit': np.random.randint(100, 200, 100)})
long_df = df.melt(id_vars='category')
sns.barplot(data=long_df, x='category', y='value', hue='variable', order=[*'abcdefg'], ci=None)
plt.show()
如果您确实需要表示置信区间的误差线,请省略 ci=None
。
我无法分享我的数据集,但它看起来像这样。
类别 | 销售额 | 利润 |
---|---|---|
(7种) | (浮动) | (浮动) |
实际上有 6 列带有数值变量。我想在 python 上将其绘制为分组条形图,其中类别作为 x 轴,各个条形线表示数字列的平均值。 seaborn 的 catplot 中的 hue 参数只接受分类值,所以我不能使用它。
还有其他方法可以绘制吗?
Seaborn 更喜欢 "long form". You can use df.melt(id_vars='category')
中的数据来转换数据帧。
这是一个例子:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
sns.set()
df = pd.DataFrame({'category': np.random.choice([*'abcdefg'], 100),
'sales': np.random.randint(1000, 2000, 100),
'profit': np.random.randint(100, 200, 100)})
long_df = df.melt(id_vars='category')
sns.barplot(data=long_df, x='category', y='value', hue='variable', order=[*'abcdefg'], ci=None)
plt.show()
如果您确实需要表示置信区间的误差线,请省略 ci=None
。