Matplotlib - Different tick label alignment along the same axis

六眼飞鱼酱① 提交于 2020-02-22 12:46:18

问题


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')

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.

Hope I'm clear !

Any ideas ?


回答1:


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()



来源:https://stackoverflow.com/questions/49412218/matplotlib-different-tick-label-alignment-along-the-same-axis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!