Matplotlib - How to set the distance (in mm / cm / dots ...) between xticks

I watched the Internet for a long time, but could not figure out how to do it. I need to draw some numbers whose xticks are defined as numpy.arange (1, N), N for each figure is different. I want the distance between xticks to be the same in all figures (for example, 1 cm), that is, the width of each figure should depend on the size of numpy.arange (1, N). Any idea how to do this?

+6
source share
2 answers

I think you can do this with a combination of careful control of the size of your axes (as part of the figure), ax.set_xlim and fig.set_size_inches (doc) to set the actual size of the figure.

ex

  fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.set_xlim([0,N]) fig.set_size_inches([N/2.54,h]) 
+2
source

To expand on @tcaswell's answer, here is how I do it when I want to micro-control the real size of my axis and the distance between ticks.

 import numpy as np import matplotlib.pyplot as plt plt.close('all') #------------------------------------------------------ define xticks setup ---- xticks_pos = np.arange(11) # xticks relative position in xaxis N = np.max(xticks_pos) - np.min(xticks_pos) # numbers of space between ticks dx = 1 / 2.54 # fixed space between xticks in inches xaxis_length = N * dx #------------------------------------------------------------ create figure ---- #---- define margins size in inches ---- left_margin = 0.5 right_margin = 0.2 bottom_margin = 0.5 top_margin = 0.25 #--- calculate total figure size in inches ---- fwidth = left_margin + right_margin + xaxis_length fheight = 3 fig = plt.figure(figsize=(fwidth, fheight)) fig.patch.set_facecolor('white') #---------------------------------------------------------------- create axe---- #---- axes relative size ---- axw = 1 - (left_margin + right_margin) / fwidth axh = 1 - (bottom_margin + top_margin) / fheight x0 = left_margin / fwidth y0 = bottom_margin / fheight ax0 = fig.add_axes([x0, y0, axw, axh], frameon=True) #---------------------------------------------------------------- set xticks---- ax0.set_xticks(xticks_pos) plt.show(block=False) fig.savefig('axis_ticks_cm.png') 

This results in a 11.8 cm pattern with xaxis 10 cm with 1 cm space between each tick:

enter image description here

0
source

Source: https://habr.com/ru/post/923504/


All Articles