问题
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