【问题标题】:Detect when matplotlib tick labels overlap检测 matplotlib 刻度标签何时重叠
【发布时间】:2017-09-20 12:14:28
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-14
      • 2020-01-05
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 2019-05-11
      • 2013-07-21
      • 1970-01-01
      相关资源
      最近更新 更多