python - 将 x 轴刻度标签向左移动一位

标签 python matplotlib bar-chart

<分区>

我正在制作条形图,我想将 x 轴刻度标签向左移动一个位置。这是情节的代码:

matplotlib.rcParams.update(matplotlib.rcParamsDefault)
plt.style.use(['seaborn-white', 'bmh'])

fig1, ax = plt.subplots()

palette = ['#2a5495', '#07a64c', '#e979ad', '#d88432', '#2a5495',
               '#b7040e', '#82c5db', '#b9c09b', '#cd065d', '#4b117f']

x = np.array(df.index)
y = np.array(df.loc[:, 2015])

width = 1.0
lefts = [x * width for x, _ in enumerate(y)]
ax.bar(left = lefts, height = y, width = width, tick_label = x, color = palette, label = ranked_univs)

ax.axis(ymin = 0, ymax = 200, xmin = -0.5, xmax = 9.5)
ax.tick_params(axis='x', which='major', labelsize=8)
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)

fig1.tight_layout()
plt.show()

这是条形图:

enter image description here

有什么线索吗?

最佳答案

您的标签已正确定位,事实表明,如果您将它们旋转 90°,它们将与您的条形图完美对齐。

fig1, ax = plt.subplots()

palette = ['#2a5495', '#07a64c', '#e979ad', '#d88432', '#2a5495',
               '#b7040e', '#82c5db', '#b9c09b', '#cd065d', '#4b117f']

labels = ['Long misaligned label {}'.format(i) for i in range(10)]
x = range(10)
y = 100+100*np.random.random((10,))

width = 1.0
lefts = [x * width for x, _ in enumerate(y)]
ax.bar(left = lefts, height = y, width = width, tick_label = labels, color = palette)

ax.axis(ymin = 0, ymax = 200, xmin = -0.5, xmax = 9.5)
ax.tick_params(axis='x', which='major', labelsize=8)
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=90)

fig1.tight_layout()
plt.show()

enter image description here

问题是标签水平居中,因此当您将它们旋转 45° 时,它们似乎与错误的条对齐。要解决此问题,请将标签右对齐,它们将回到正确的(视觉)位置。

plt.setp(ax.xaxis.get_majorticklabels(), ha='right')

enter image description here

另一个(可能更简单)选项是使用 helper function Figure.autofmt_xdate() ,它会为您处理所有这一切。

关于python - 将 x 轴刻度标签向左移动一位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43520322/

相关文章:

python - 什么时候可以动态地向对象添加字段?

python - 使用 LineCollection 绘制 shapefile 显示所有边缘,但部分填充它们

javascript - 在chartjs的条形顶部添加图像

r - 是否有 ggplot 函数用于为不同渐变的堆叠条形图中的子组着色?

具有 3 个变量的 R 条形图

python - 如何从url获取html标签?

Python 3.2.2 从控制台读取

python - 如何从列表列创建组合的 Pyspark Dataframe

python - 在 matplotlib 3d 中旋转 STL 文件

python - 在 python matplotlib 中格式化断开的 y 轴