带seaborn的可变宽度条形图

2024-04-25 00:14:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Seaborn创建一个带有可变宽度x轴箱子的条形图。与此图表类似: enter image description here 我所有的x宽度加起来会达到100%,但我似乎找不到一个例子来说明如何通过Seaborn实现这个目标。有什么想法吗?在


Tags: 目标宽度图表seaborn例子条形图箱子
2条回答

这里可能有几个可能的答案。在seaborn条形图中,您可以使用几个参数的组合:“width”(条形图的宽度值)、“left”(x轴上的位置值,这是必需的参数)和“align”。在

一个非常简单的例子:

import seaborn as sns

data = [7, 3, 15]
widths = [1, 5, 3]
left = [0, 1, 6]
sns.plt.bar(left, data, width = widths, color=('orange','green','blue'), 
alpha = 0.6, align='edge', edgecolor = 'k', linewidth = 2)

请注意,“左”(杆的位置)应与宽度相对应,以使杆仅接触而不重叠。在

enter image description here

如果要将Seaborn用于条形图,则需要在之后更改条形图矩形(面片)的宽度(这是通过matplotlib面向对象接口按照this answer完成的):

import seaborn as sns

iris = sns.load_dataset('iris')
ax = sns.barplot('species', 'sepal_width', data=iris)
widthbars = [0.3, 0.6, 1.2]
for bar, newwidth in zip(ax.patches, widthbars):
    x = bar.get_x()
    width = bar.get_width()
    centre = x + width/2.
    bar.set_x(centre - newwidth/2.)
    bar.set_width(newwidth)

enter image description here

也可以在matplotlib中直接创建类似的条形图:

^{pr2}$

enter image description here

相关问题 更多 >