Python 如何在 matplotlib 中旋转 xticklabels 以使每个 xticklabel 之间的间距相等?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43152502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I rotate xticklabels in matplotlib so that the spacing between each xticklabel is equal?
提问by Franck Dernoncourt
How can I rotate xticklabels in matplotlib so that the spacing between each xticklabel is equal?
如何在 matplotlib 中旋转 xticklabels 以使每个 xticklabel 之间的间距相等?
For example with this code:
例如使用此代码:
import matplotlib.pyplot as plt
import numpy as np
# Data + parameters
fontsize = 20
t = np.arange(0.0, 6.0, 1)
xticklabels = ['Full', 'token emb', 'char emb', 'char LSTM',
'token LSTM', 'feed forward','ANN']
# Plotting
fig = plt.figure(1)
ax = fig.add_subplot(111)
plt.plot(t, t)
plt.xticks(range(0, len(t) + 1))
ax.tick_params(axis='both', which='major', labelsize=fontsize)
ax.set_xticklabels(xticklabels, rotation = 45)
fig.savefig('test_rotation.png', dpi=300, format='png', bbox_inches='tight')
I obtain:
我获得:
The spacing between each xticklabel is unequal. For example, the spacing between 'Full' and 'token emb' is much larger than the spacing between 'feed forward' and 'ANN'.
每个 xticklabel 之间的间距是不等的。例如,“Full”和“token emb”之间的间距远大于“feed forward”和“ANN”之间的间距。
I use Matplotlib 2.0.0 and Python 3.5 64-bit on Windows 7 SP1 x64 Ultimate.
我在 Windows 7 SP1 x64 Ultimate 上使用 Matplotlib 2.0.0 和 Python 3.5 64 位。
回答by ImportanceOfBeingErnest
The labels are centered at the tickmark position. Their bounding boxes are unequal in width and might even overlap, which makes them look unequally spaced.
标签以刻度线位置为中心。它们的边界框宽度不等,甚至可能重叠,这使它们看起来不等距。
Since you'd always want the ticklabels to link to their tickmarks, changing the spacing is not really an option.
由于您总是希望刻度标签链接到它们的刻度线,因此更改间距并不是一个真正的选择。
However you might want to align them such the the upper right corner is the reference for their positioning below the tick.
但是,您可能希望将它们对齐,这样右上角是它们在刻度下方定位的参考。
Use the horizontalalignment
or ha
argument for that and set it to "right"
:
为此使用horizontalalignment
or ha
参数并将其设置为"right"
:
ax.set_xticklabels(xticklabels, rotation = 45, ha="right")
This results in the following plot:
这导致以下情节:
An alternative can be to keep the ticklabels horizontally centered, but also center them vertically. This leads to an equal spacing but required to further adjust their vertical position with respect to the axis.
另一种方法是保持刻度标签水平居中,但也垂直居中。这导致了相等的间距,但需要进一步调整它们相对于轴的垂直位置。
ax.set_xticklabels(xticklabels, rotation = 45, va="center", position=(0,-0.28))
The above can be used if the ticks are specified manually like in the question (e.g. via plt.xticks
or via ax.set_xticks
) or if a categorical plot is used.
If instead the labels are shown automatically, one should not useset_xticklabels
. This will in general let the labels and tick positions become out of sync, because set_xticklabels
sets the formatter of the axes to a FixedFormatter
, while the locator stays the automatic AutoLocator
, or any other automatic locator.
如果像问题中一样手动指定刻度线(例如 viaplt.xticks
或 via ax.set_xticks
)或者使用分类图,则可以使用上述内容。
如果标签是自动显示的,则不应使用set_xticklabels
. 这通常会使标签和刻度位置变得不同步,因为set_xticklabels
将轴的格式化程序设置为 a FixedFormatter
,而定位器保持自动AutoLocator
或任何其他自动定位器。
In those cases either use plt.setp
to set the rotation and alignment of existing labels,
在这些情况下,要么用于plt.setp
设置现有标签的旋转和对齐,
plt.setp(ax.get_xticklabels(), ha="right", rotation=45)
or loop over them to set the respective properties,
或遍历它们以设置相应的属性,
for label in ax.get_xticklabels():
label.set_ha("right")
label.set_rotation(45)
An example would be
一个例子是
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
t = np.arange("2018-01-01", "2018-03-01", dtype="datetime64[D]")
x = np.cumsum(np.random.randn(len(t)))
fig, ax = plt.subplots()
ax.plot(t, x)
for label in ax.get_xticklabels():
label.set_ha("right")
label.set_rotation(45)
plt.tight_layout()
plt.show()