Matplotlib-沿着同一轴的不同刻度标记对齐方式 [英] Matplotlib - Different tick label alignment along the same axis

查看:354
本文介绍了Matplotlib-沿着同一轴的不同刻度标记对齐方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有很多子图的图形,因此,轴的最后一个刻度标签被写在下一个刻度的第一个刻度标签上. 在此处查看示例

I have a figure with a lot of subplot, such that the last ticklabel of an axis is written over the first tick label of the next one. See example here

由于我想保持子图之间的间距不变,因此我希望根据刻度线进行不同的对齐,因为它可能是由:

As I want to keep the spacing between the subplots as I set it, I would like to have a different alignment depending on the tick, as it could be produced by :

    plt.xticks([0], ha = 'left')
    plt.xticks([0.2,0.4], ha = 'center')
    plt.xticks([0.6], ha = 'right')

使用该选项,图中仅显示xticks的最后一次调用.换句话说,想法是对齐第一个和最后一个刻度标签,使它们保持在子图中.

Using that, only the last call of xticks is shown on the figure. In another way, the idea is to align first and last tick labels such that they stay within the subplot.

希望我很清楚!

有什么想法吗?

推荐答案

一旦修复了刻度,便可以访问并设置刻度标签的对齐方式,以免相邻子图之间出现重叠.

Once you fix the ticks, you will be able to access and set the ticklabels' alignment as you wish to avoid overlapping between neighboring subplots.

import matplotlib.pyplot as plt

plt.rcParams.update({"xtick.direction" : "in", 
                     "ytick.direction" : "in",
                     "figure.subplot.wspace" : 0.02,
                     "axes.xmargin" : 0,
                     "figure.figsize" : (5,2.4)})

fig, axes = plt.subplots(1,2, sharey=True)
for ax in axes:
    ax.plot([0,.3,.6], [0,1,2])
    # Fix ticks
    ax.set_xticks([0,.2,.4,.6])
    # Get ticklabels for fixed ticks
    ticklabels = ax.get_xticklabels()
    # set the alignment for outer ticklabels
    ticklabels[0].set_ha("left")
    ticklabels[-1].set_ha("right")

plt.show()

这篇关于Matplotlib-沿着同一轴的不同刻度标记对齐方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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