【问题标题】:Moving matplotlib xticklabels by pixel value按像素值移动 matplotlib xticklabels
【发布时间】:2018-06-27 19:29:38
【问题描述】:

如何将刻度标签移动几个像素?

在我的例子中,我想将 X 轴上的 This is class #N-标签向右移动几个像素。

我是aware of thehorizontalalign/harightcenterleft;但我想“改进”right 对齐的外观。

以下面的例子为例,它将产生如下图:

import pandas as pd
import numpy as np

categories = ['This is class #{}'.format(n) for n in range(10)]
data = {
    'Value': [categories[np.random.randint(10)] for _ in range(100)], 
    'id': [1000+i for i in range(100)]
}

df = pd.DataFrame(data)

ax = df.Value.value_counts().sort_index().plot(kind='bar', rot=45)
plt.xticks(ha='right')

结果:

我主观上认为,如果将标签平移到右侧以便将勾号放在“#”上,那么情节会更好看。换言之,rightcenter 对齐选项之间的“中间地带”。

旁注

我正在使用 pandas,但我认为这与问题无关,因为它无论如何都在使用 matplotlib 进行绘图。

plt.xticks() 方法用于简单起见,我也可以使用ax.set_xticklabels(),但我不需要重写标签文本,并且 AFAIK 没有设置水平对齐的快捷方式,而无需复制现有标签使用ax.set_xticklabels(labels, **more_options),因为ha 不是有效的key in matplotlib 2ax.xaxis.set_tick_params() 方法。

我知道 pandas 的 Series.hist()-方法,但我认为 Series.value_counts().plot(kind='bar') 看起来更漂亮,因为我的类别很少,并且希望栏的数量与类别的数量相同。

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    为了将刻度标签移动几个像素,您可以在其转换链中添加平移。例如。要向右移动 20 像素,请使用

    import matplotlib.transforms as mtrans
    # ...
    trans = mtrans.Affine2D().translate(20, 0)
    for t in ax.get_xticklabels():
        t.set_transform(t.get_transform()+trans)
    

    如果您需要移动以使#-符号位于刻度线下方的像素数当然不是事先明确的 - 这需要通过反复试验来找出。或者,您可能对要在其他单位中移动多少有不同的提示。

    这是完整的例子,

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    import matplotlib.transforms as mtrans
    
    categories = ['This is class #{}'.format(n) for n in range(10)]
    data = {
        'Value': [categories[np.random.randint(10)] for _ in range(100)], 
        'id': [1000+i for i in range(100)]
    }
    
    df = pd.DataFrame(data)
    
    ax = df.Value.value_counts().sort_index().plot(kind='bar', rot=45)
    plt.xticks(ha='right')
    
    trans = mtrans.Affine2D().translate(20, 0)
    for t in ax.get_xticklabels():
        t.set_transform(t.get_transform()+trans)
    
    plt.tight_layout()
    plt.show()
    

    生产

    【讨论】:

    • 这和描述的一样完美。带有完整示例和图像的好答案。
    • 由于某种原因,我得到了预期的结果,但如果我使用“savefig”,保存的图像没有预期的翻译。
    猜你喜欢
    • 2011-09-14
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多