如何解决Seaborn-具有Bottom参数的分组条形图
我想使用seaborn创建一个条形图(垂直),每个x轴标签将具有n个(在示例中为2个)不同颜色的条形-但是每个条形都是浮动的-换句话说,它使用matplotlib条形底部参数
这没有下面的部分,但失败了
import pandas as pd
import seaborn as sns
d = {'month':['202001','202002','202003','202001','202003'],'range' : [0.94,4.47,0.97,4.70,0.98,1.23],'bottom' : [8.59,17.05,8.35,17.78,8.32,5.67],'group' : ['a','a','b','b']
}
df = pd.DataFrame(data=d)
sns.barplot(data=df,x = "month",y = "range",hue='group')
(抱歉,由于某些原因我无法上传图片,我认为该服务已被我的工作屏蔽,但如果运行该代码,它将显示该图片)
但是当我添加底部参数时,它会失败
sns.barplot(data=df,hue='group',bottom='bottom')
我很感谢您的帮助,也许是从逻辑上应该解释它为什么失败的解释
条形图表示度量的预测范围,我想将其显示为矩形
解决方法
sns
本身不处理bottom
,因此将其传递给plt.bar
。但是plt.bar
要求bottom
与x
和y
具有相同的形状/大小,而sns
传递数据时则不是这种情况。
让我们尝试使用熊猫图功能:
to_plot = df.pivot(index='month',columns='group')
fig,ax = plt.subplots()
to_plot['range'].add(to_plot['bottom']).plot.bar(ax=ax)
# cover the bars up to `bottom`
# replace `w` with background color of your choice
to_plot['bottom'].plot.bar(ax=ax,color='w',legend=None)
输出:
sns.set() to_plot = df.pivot(index ='month',columns ='group')
对于允许特定样式的另一种方法:
# set sns plot style
sns.set()
fig,ax = plt.subplots()
for i,(label,r) in enumerate(to_plot.iterrows()):
plt.bar([i-0.1,i+0.1],r['range'],bottom=r['bottom'],color=['C0','C1'],width=0.2)
plt.xticks(np.arange(len(to_plot)),to_plot.index);
输出:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。