没有简单的方法来确定标签是否重叠。
一种可能的解决方案可能是根据字符串中字符的数量来决定旋转标签。如果有很多字符,很可能会出现重叠标签。
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()
就我个人而言,我会选择旋转所有标签的解决方案,但仅旋转 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()