Detect when matplotlib tick labels overlap

冷暖自知 提交于 2021-02-05 07:09:22

问题


I have a matplotlib bar chart generated by pandas, like this:

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)

As you can see, with 0 rotation, the xtick labels overlap. How can I detect when two labels overlap, and rotate just those two labels to 90 degrees?


回答1:


There is no easy way to determine if labels overlap.

A possible solution might be to decide upon rotating the label on the basis of the number of charaters in the string. If there are a lot of characters, chances are high that there would be overlapping labels.

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()

Personally I would opt for a solution which rotates all of the labels, but only by 15 degrees or so,

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()



来源:https://stackoverflow.com/questions/43577502/detect-when-matplotlib-tick-labels-overlap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!