检测matplotlib刻度标签何时重叠 [英] Detect when matplotlib tick labels overlap

查看:72
本文介绍了检测matplotlib刻度标签何时重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由熊猫生成的matplotlib条形图,如下所示:

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)

如您所见,旋转0时,xtick标签重叠.如何检测两个标签何时重叠,并将这两个标签旋转90度?

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?

推荐答案

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

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

我个人会选择一种解决方案,该解决方案可以旋转所有标签,但只能旋转15度左右,

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

这篇关于检测matplotlib刻度标签何时重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆