按像素值移动matplotlib xticklabels [英] Moving matplotlib xticklabels by pixel value

查看:199
本文介绍了按像素值移动matplotlib xticklabels的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I move tick labels by a few pixels?

在我的情况下,我想将这是X轴上的#N 类标签向右移动几个像素.

In my case, I want to move the This is class #N-labels on the X-axis to the right by a few pixels.

知道 horizontalalign/harightcenterleft;但我想改善" right对齐方式的外观.

I am aware of the horizontalalign/ha values right, center, and left; but I want to "improve" the looks of the right alignment.

以下面的示例为例,将产生如下所示的图:

Take the following example which will produce the plot shown below:

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对齐选项之间的中间立场".

I think, subjectively, that the plot would look better if the labels were translated to the right so that the tick were placed over the "#". In other words, a "middle ground" between the right and center alignment options.

旁注:

我正在使用熊猫,但我认为这与问题无关,因为它还是使用matplotlib进行绘制.

I'm using pandas, but I believe that is irrelevant to the issue, as it's using matplotlib to do its plotting anyway.

为了简便起见,使用了plt.xticks()方法,我也可以使用ax.set_xticklabels(),但是我不需要重写标签文本,并且AFAIK没有设置复制水平对齐方式的快捷方式由于ha不是有效的键入matplotlib 2 ax.xaxis.set_tick_params()-方法.

The plt.xticks() method is used for simplicity, I could just as well use ax.set_xticklabels(), but I don't need to rewrite the label texts, and AFAIK there is no shortcut to set the horizontal alignment without also copying the existing labels into with ax.set_xticklabels(labels, **more_options), as ha is not a valid key in matplotlib 2's ax.xaxis.set_tick_params()-method.

我知道大熊猫的Series.hist()方法,但是我认为Series.value_counts().plot(kind='bar')在类别很少并且希望条形数量与类别数量相同时看起来更漂亮.

I'm aware of pandas' Series.hist()-method, but I think the Series.value_counts().plot(kind='bar') looks prettier when I have few categories and want the number of bars to be the same as number of categories.

推荐答案

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

In order to move the ticklabels by a few pixels you may add a translation to their transformation chain. E.g. to move by 20 pixels to the right, use

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

当然,如果为了使#号位于刻度线下方而需要移动的像素数不是先验的-需要通过反复试验找出.或者,也许您对要转换其他单位的数量有不同的提示.

If course the number of pixels that you need to shift in order for the #-sign to be under the tickmark is not a priori clear - that needs to be found out via trial and error. Or maybe you have a different hint on by how much you want to shift in what other units.

这是完整的示例,

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

生产

这篇关于按像素值移动matplotlib xticklabels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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