将特定的 x 标签彼此不同地对齐? [英] Align specific x labels differently to each other?

查看:43
本文介绍了将特定的 x 标签彼此不同地对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究这个情节:

从概念上讲,想从此更改x标签的位置:

为此:

有这样的功能吗?我需要手动更改标签的位置吗?

我不想使用:

  plt.margins(x = 0.04)

因为它也会移动我的数据,而且我需要,2006 年右移,2018 年左移.

解决方案

您可以使用面向对象的API稍微深入地研究matplotlib滴答的工作原理.

首先,您可以使用

I am working on this plot:

Conceptually, would like to change x labels position from this:

to this:

Is there a function for that? Do I need to manually change the position of my label and if so how?

I don't want to use :

plt.margins(x=0.04)

because it shifts my data as well, and I need, just 2006 shifted right and just 2018 shifted left.

解决方案

You do this by digging slightly deeper into the workings of matplotlib ticks using the object oriented API.

First off, you can get a list of your major ticks using xaxis.get_major_ticks(). This returns a list of matplotlib.axis.XTick objects. These have an attribute label1 which is the label of the tick. This is a Text instance which has a property set_horizontalalignment(align). Which states:

set_horizontalalignment(align)

Set the horizontal alignment to one of

ACCEPTS: [ ‘center’ | ‘right’ | ‘left’ ]

Then, as you only want to modify the first and last ticks, simply set the alignment of the specific ticks using the first and last entries in the list.

A working example:

import matplotlib.pyplot as plt

x = [1,2,3]
y = [4,5,6]

labels = ["2004", "2006", "2008"]

fig, ax = plt.subplots()
ax.margins(0)
ax.plot(x,y)
ax.set_xticks(x)
ax.set_xticklabels(labels)
# above code recreates the issue

# get list of x tick objects
xTick_objects = ax.xaxis.get_major_ticks()

xTick_objects[0].label1.set_horizontalalignment('left')   # left align first tick 
xTick_objects[-1].label1.set_horizontalalignment('right') # right align last tick

plt.show() 

Which gives:

这篇关于将特定的 x 标签彼此不同地对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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