Skip to main content
 首页 » 编程设计

python之检测 matplotlib 刻度标签何时重叠

2024年10月01日8bonelee

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

如您所见,旋转 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() 

我个人会选择旋转所有标签的解决方案,但只能旋转 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()