检测 matplotlib 刻度标签何时重叠

2023-12-14

我有一个由 pandas 生成的 matplotlib 条形图,如下所示:

index = ["Label 1", "Label 2", "Lorem ipsum dolor sit amet", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis ac vehicula leo, vitae sodales orci."]
df = pd.DataFrame([1, 2, 3, 4], columns=["Value"], index=index)
df.plot(kind="bar", rot=0)

bar chart

如您所见,旋转 0 时,xtick 标签重叠。如何检测两个标签何时重叠,并将这两个标签旋转 90 度?


没有简单的方法来确定标签是否重叠。

一种可能的解决方案可能是根据字符串中字符的数量来决定旋转标签。如果有很多字符,很可能会出现重叠标签。

import matplotlib.pyplot as plt
import pandas as pd

index = ["Label 1", "Label 2", "Lorem ipsum dolor sit amet", "Duis ac vehicula leo, vitae sodales orci."]
df = pd.DataFrame([1, 2, 3, 4], columns=["Value"], index=index)
ax = df.plot(kind="bar", rot=0)

threshold = 30
for t in ax.get_xticklabels():
    if len(t.get_text()) > threshold:
        t.set_rotation(90)

plt.tight_layout()
plt.show()

enter image description here

就我个人而言,我会选择旋转所有标签的解决方案,但仅旋转 15 度左右,

import matplotlib.pyplot as plt
import pandas as pd

index = ["Label 1", "Label 2", "Lorem ipsum dolor sit amet", "Duis ac vehicula leo, vitae sodales orci."]
df = pd.DataFrame([1, 2, 3, 4], columns=["Value"], index=index)
ax = df.plot(kind="bar", rot=15)
plt.setp(ax.get_xticklabels(), ha="right")

plt.tight_layout()
plt.show()

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检测 matplotlib 刻度标签何时重叠 的相关文章

随机推荐