Seaborn水平条形图 [英] Seaborn horizontal bar plot

查看:420
本文介绍了Seaborn水平条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认的Seaborn条形图对我几乎有效,尽管有一些细节.如下所示:

The default Seaborn barplot almost works for me albeit a few details. It is shown below:

请查看每个栏旁边和右侧的文本"注释.我需要改进一些地方:

Please look at the 'text' annotation alongside and to the right of each bar. There are a few things that I would like to improve upon:

  1. 由于某种原因,最后一个栏不显示注释.我不知道该如何解决.

  1. The last bar does NOT show the annotation for some reason. I do not know how to fix that.

条形图的边缘与X轴的顶部和底部之间没有空格.我想在那儿放些空间.

There is no space between the edges of bars and the top and bottom X axes. I would like to put some space in there.

反正条的宽度可以增加吗?

Is there anyway that the widths of the bars can be increased?

我还想增加最高"栏和右Y轴之间的距离,因为我计划添加文本,而不仅仅是添加与它们的X轴值相对应的厚度"数.如果您查看与HRA的Red0类别相对应的条,它将像105.65(42.54%).显然,它将推"到右Y轴的边缘上.有没有办法在其峰值和最大X轴值之间增加一些距离?因此,例如,如果我可以将其设置为条形的最大高度(易于计算)加上一定量.

I would also like to increase the distance between the 'tallest' bar and the right Y axis, since I am planning on adding text than just the Thickness numbers corresponding to their X axis values. It would be something like 105.65 (42.54%) if you look at the bar corresponding to Red0 category of the HRA. That will clearly push it 'over' the edge of right Y axis. Is there a way to put some more distance between its peak and the max X axis value? So for instance, if I could set it to the Max height of the bars (easy to calculate) plus a certain amount.

如果我能处理这些细节,那就完美了!

If I could take care of those details, it would make it perfect!

以下是与上述问题相关的代码片段:

Here is the snippet of my code that is relevant to the questions above:

sns.set_style('whitegrid')
sns.set(font_scale=0.8)
thickness = []
for hra_color in df_hra_colors['hra']:
    thickness.append(grouped.get_group(hra_color).count()['hra'] * mult)
df_hra_colors['thickness'] = thickness
ax = sns.barplot(x='thickness', y='hra', data=df_hra_colors,
                 palette=df_hra_colors['hex'].tolist())
ax.set_xlabel("Thickness")
ax.set_ylabel("HRA")
ax.set_title("What an Awesome Plot!")
for p in ax.patches:
    ax.annotate("%.2f" % p.get_width(), (p.get_x() + p.get_width(), p.get_y() + 1.2),
                xytext=(5, 10), textcoords='offset points')
plt.show()

以下是一个要求完整的可验证的最小示例:

Here is a minimal, complete verifiable example as requested:

""" Minimal program for demonstration """
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

def main():
    sns.set_style('whitegrid')
    sns.set(font_scale=0.8)
    # plt.rcParams['figure.figsize'] = (10,10)
    df_hra_colors = pd.DataFrame({
        'hra': ['red', 'green', 'blue'],
        'hex': ['#cc0000', '#40ff00', '#0000ff']
    })
    thickness = [1, 2, 3]
    thick_sum = sum(thickness)
    df_hra_colors['thickness'] = thickness
    ax = sns.barplot(x='thickness', y='hra', data=df_hra_colors,
                     palette=df_hra_colors['hex'].tolist())
    plt.xlim(0, max(thickness) + 30)
    ax.set_xlabel("Thickness")
    ax.set_ylabel("HRA")
    ax.set_title("What an Awesome Plot!")
    for i, p in enumerate(ax.patches):
        ax.annotate("%.2f (%.2f)%%" % (p.get_width(), thickness[i] / thick_sum * 100.0),
                    (p.get_x() + p.get_width(), p.get_y() + 1),
                    xytext=(5, 10), textcoords='offset points')
    plt.show()

if __name__ == "__main__":
    main()

这是它的外观:

然后我将添加1到p.get_y()的行更改为添加0.5,如下所示:

I then changed the line that adds 1 to p.get_y() to add 0.5 instead as shown below:

for i, p in enumerate(ax.patches):
    ax.annotate("%.2f (%.2f)%%" % (p.get_width(), thickness[i] / thick_sum * 100.0),
                (p.get_x() + p.get_width(), p.get_y() + 0.5),
                xytext=(5, 10), textcoords='offset points')

这就是我得到的:

因此,由于偏移,带注释的文本被隐藏了.利用这些知识,我可以调整原始脚本以在最后一个栏中显示带注释的文本.但这引出了另外一个问题.不知道小节数量时如何调整代码以使其一致?

So the annotated text was hidden because of the offset. Using this knowledge, I could adjust my original script to show the annotated text in the last bar. But this leads to additional question. How do you adjust the code to be consistent when you do not know the number of bars in advance?

您的答案2正常运行.谢谢.

Your answer 2 works fine. Thank you.

由于我使用的是sns.barplot,所以3号对我不起作用. Python不喜欢对barplot的调用中的width参数.

Number 3 did not work for me since I am using sns.barplot. Python does not like the width parameter in the call to barplot.

数字4可以正常工作.谢谢.

Number 4 works fine. Thank you.

感谢您对我的问题的帮助.

Thank you for your help with my questions.

推荐答案

  1. 关于第一点,我们需要一个最小,完整,可验证的示例.

为了在边条和轴之间留出空间,可以调整轴的极限. ax.set_ylim(-1,N),其中N是条数.

In order to put space between the edge bars and the axes, one can adjust the limits of the axes. ax.set_ylim(-1,N), where N is the number of bars.

条的宽度可以使用plt.barwidth参数设置. plt.bar(..., width=1);或者,对于水平条,请使用height参数.线性条形图不允许设置宽度或高度.

The width of the bars can be set with the width argument of plt.bar. plt.bar(..., width=1); or, for horizontal bars, use the height argument. The seaborn bar plot does not allow to set the width or height.

与2相同,只是与ax.set_xlim(0,barmax*1.4)相同,其中barmax是钢筋的最大长度.

Same as 2, just with ax.set_xlim(0,barmax*1.4), where barmax is the maximum length of the bar.

这篇关于Seaborn水平条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆