首页 > 解决方案 > 在更改计数图的条形宽度时,条形的相对位置会从 x 刻度偏移。我们如何解决这个问题?

问题描述

我正在尝试使用 seaborn 显示计数图,但条形的宽度非常高,而且图看起来不太好。为了解决这个问题,我使用以下代码片段更改了绘图的宽度:

sns.set()
fig,ax = plt.subplots(figsize=(10,4))
sns.countplot(x=imdb_data["label"],ax=ax)
for patch in ax.patches:
    height = p.get_height()
    width = patch.get_width
    p.set_height(height*0.8)
    patch.set_width(width*0.4)
    x      = p.get_x()
    ax.text(x = x+new_width/2.,y= new_height+4,s = height,ha="center")

ax.legend(labels=("Negative","Positive"),loc='lower right')
plt.show()

但是这样做后,x-tick 标签会发生变化,并且情节看起来像所附图像中所示的那样。

在此处输入图像描述

我应该如何更改宽度,x-tick 位置也根据栏的新宽度自动更改?. 图例也没有正确显示。我使用下面的代码片段来添加图例:

plt.legend(labels=['Positive','Negative'],loc='lower right')

请帮帮我。

标签: pythonpython-3.xmatplotlibseaborndata-visualization

解决方案


为了使条形图保持居中,您还需要将x位置更改为新旧宽度差的一半。更改高度似乎不是一个好主意,因为 y 轴上的标签会不匹配。如果更改高度的主要原因是为文本腾出空间,那么更改y限制会更容易,例如通过ax.margins(). 垂直对齐文本'bottom'允许忽略该y位置的任意偏移量。

可以通过循环遍历补丁并一一设置标签来设置图例的标签。由于每个条形的 x 轴已经有不同的位置,因此最好省略图例并更改 x 刻度标签?

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

sns.set()
imdb_data = pd.DataFrame({"label": np.random.randint(0, 2, 7500)})

fig, ax = plt.subplots(figsize=(10, 4))
sns.countplot(x=imdb_data["label"], ax=ax)
for patch, label in zip(ax.patches, ["Negative", "Positive"]):
    height = patch.get_height()
    width = patch.get_width()
    new_width = width * 0.4
    patch.set_width(new_width)
    patch.set_label(label)
    x = patch.get_x()
    patch.set_x(x + (width - new_width) / 2)
    ax.text(x=x + width/2, y=height, s=height, ha='center', va='bottom')
ax.legend(loc='lower right')
ax.margins(y=0.1)
plt.tight_layout()
plt.show()

结果图

PS:要更改 x 刻度标签,以便可以使用它们代替图例,请添加

ax.set_xticklabels(['negative', 'positive'])

并省略ax.legend()andpatch.set_label(label)行。


推荐阅读