python - 在更改计数图的条形宽度时,条形的相对位置会从 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')
请帮帮我。
解决方案
为了使条形图保持居中,您还需要将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)
行。
推荐阅读
- c# - 为什么不编译?无法从“X”转换?到“X”
- c# - 在 C# 中是否可以通过属性存在进行模式匹配?
- python - 当我们在 Python 中不提及类时
- istio - ISTIO External Auth : '503 上游连接错误或在标头之前断开/重置。重置原因:通过 HTTPS 访问时连接终止根'
- android-studio - 我如何在 android studio 的 kotlin aproject 中使用 java jep perser?
- javascript - 如何在箱线图高图中将函数设置为最大值
- checkbox - 在反应中打开和关闭模式后如何保存复选框的标记?
- apache-nifi - 使用 NiFi 处理器计算文件中的文件数和行数
- linux - 删除固定宽度文件中的重复项,该文件除最后一次出现外具有多个键列
- java - Liferay 7.3 - org.hibernate.MappingException:找不到实体类