简体   繁体   English

如何对齐 matplotlib 中的刻度标签?

[英]How do you align tick labels in matplotlib?

I'm trying to build an infographic using matplotlib, and I want to left-align all the y-axis' tick labels.我正在尝试使用 matplotlib 构建信息图,并且我想左对齐所有 y 轴的刻度标签。

在此处输入图像描述

I want to move all the tick labels to the left — I want them all to begin from the same x-location as District of Columbia .我想将所有刻度标签向左移动——我希望它们都从与District of Columbia相同的 x 位置开始。

I tried to do that using Axes.set_yticklabels , but I can't figure out how to do it.我尝试使用Axes.set_yticklabels来做到这一点,但我不知道该怎么做。

A flexible approach is to plot the labels separately, with ax.text() .一种灵活的方法是 plot 标签分别使用ax.text() Here is a simple example:这是一个简单的例子:

import matplotlib.pyplot as plt

y = [0, 1, 2]
width = [2, 2, 3]
labels = ['Colorado', 'Massachusetts', 'DC']

fig, ax = plt.subplots()
ax.barh(y=y, width=width)
ax.set_yticks(y)
ax.set_yticklabels([]) 

for i, yi in enumerate(y):
    ax.text(-0.8, yi, labels[i], horizontalalignment='left', verticalalignment='center')

标签对齐示例

Just adjust the offset ( -0.8 in the example above) according to your longest label.只需根据您最长的 label 调整偏移量(上例中为-0.8 )。

Did you try using the set_horizontalalignment() for each tick on the axis?您是否尝试对轴上的每个刻度使用set_horizontalalignment()

for tick in ax.yaxis.get_majorticklabels():
    tick.set_horizontalalignment("left")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM