python - matplotlib 和/或 seaborn 中旋转轴标签的均匀间距

标签 python matplotlib seaborn

旋转解决方案here和/或 here对于长度相似的标签效果很好。然而,位置似乎是基于标签的中间,因此如果标签名称的长度不均匀,则间距会关闭。

以下代码会产生不均匀间隔的外观。

frame = pd.DataFrame(np.random.random((10, 4)), columns=[
    'Medium Name', 'Really Really Long Name', 'Name', 
    'Ridiculously Good Looking and Long Name'
])
ax = sns.barplot(data=frame)
plt.xticks(rotation=45)

我尝试调整类似于 this question 的间距,但要使其看起来正确,这是一个烦人的手动猜测过程。添加行 ax.axes.set_xticks([-0.2,0.6,2,2.3])大致创建了我认为合适的间距(字符串末端位于列中心),但是是否有一种基于标签末端而不是中间的自动居中方法?或者也许将字符串包裹起来,使所有标签的长度相同?

编辑: 要显示即使对于合理长度的标签也会发生什么:

cols = ['Tag' + str(i) for i in range(8)]
cols[2] = 'Not Crazy Long'
cols[4] = 'Also Not Too Bad'
frame = pd.DataFrame(np.random.random((10, 8)), columns=cols)
ax = sns.barplot(data=frame)
plt.xticks(rotation=35)

Result here

我喜欢文本换行解决方案,但正如 @mwaskom 指出的那样,我想我真的想要标签的“向右水平对齐”(即使使用文本换行)。这可能吗?

最佳答案

如果您想使用textwrap您可以获得列的平均长度并将其用作包装值:

import numpy as np, seaborn as sns
import textwrap

columns=['Medium Name', 'Really Really Long Name', 'Name',
         'Ridiculously Good Looking and Long Name']
mean_length = np.mean([len(i) for i in columns])
columns = ["\n".join(textwrap.wrap(i,mean_length)) for i in columns]
frame = pd.DataFrame(np.random.random((10, 4)), columns=columns)
ax = sns.barplot(data=frame)
ax.set_xticklabels(ax.get_xticklabels(),rotation=45,ha="right",rotation_mode='anchor')
plt.tight_layout()
plt.show()

结果: enter image description here

关于python - matplotlib 和/或 seaborn 中旋转轴标签的均匀间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43618423/

相关文章:

python - Seaborn:标注线性回归方程

python - 在 Python 中插入缺失数据并记住 x 值

python - 从 bazel genrule 调用 gcloud

python - 在 python 中绘制,在键盘点击时更新

python - 我认为 matplotlib 中的所有内容都是 QWidget。显然图不是。我的界面接受 QWidgets。该怎么办?

python - Seaborn FacetGrid 绘制两个相邻的不同 y 轴

python - LinearRegression() 和 Ridge(alpha=0) 的区别

python-3.x - Python - 从 URL 读取图像以调整图像大小并将图像转换为灰度

python - matplotlib 文本 bbox 的特定边距

python - 向 Seaborn 因子图添加数据标签