检测matplotlib刻度标签何时重叠

时间:2017-04-23 23:10:17

标签: python pandas matplotlib bar-chart axis-labels

我有一个由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度?

1 个答案:

答案 0 :(得分:2)

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

一种可能的解决方案可能是根据字符串中的字符数来决定旋转标签。如果有很多角色,那么标签重叠的可能性很高。

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