Change the Spacing of Tick Marks on the Axis of a Plot

Change the spacing of tick marks on the axis of a plot?

There are at least two ways for achieving this in base graph (my examples are for the x-axis, but work the same for the y-axis):

  1. Use par(xaxp = c(x1, x2, n)) or plot(..., xaxp = c(x1, x2, n)) to define the position (x1 & x2) of the extreme tick marks and the number of intervals between the tick marks (n). Accordingly, n+1 is the number of tick marks drawn. (This works only if you use no logarithmic scale, for the behavior with logarithmic scales see ?par.)

  2. You can suppress the drawing of the axis altogether and add the tick marks later with axis().

    To suppress the drawing of the axis use plot(... , xaxt = "n").

    Then call axis() with side, at, and labels: axis(side = 1, at = v1, labels = v2). With side referring to the side of the axis (1 = x-axis, 2 = y-axis), v1 being a vector containing the position of the ticks (e.g., c(1, 3, 5) if your axis ranges from 0 to 6 and you want three marks), and v2 a vector containing the labels for the specified tick marks (must be of same length as v1, e.g., c("group a", "group b", "group c")). See ?axis and my updated answer to a post on stats.stackexchange for an example of this method.

Changing the tick frequency on x or y axis in matplotlib

You could explicitly set where you want to tick marks with plt.xticks:

plt.xticks(np.arange(min(x), max(x)+1, 1.0))

For example,

import numpy as np
import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()

(np.arange was used rather than Python's range function just in case min(x) and max(x) are floats instead of ints.)


The plt.plot (or ax.plot) function will automatically set default x and y limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim() to discover what limits Matplotlib has already set.

start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))

The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example,

ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))

Here's a runnable example:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()

How to change spacing between ticks in matplotlib?

The spacing between ticklabels is exclusively determined by the space between ticks on the axes. Therefore the only way to obtain more space between given ticklabels is to make the axes larger.

In order to determine the space needed for the labels not to overlap, one may find out the largest label and multiply its length by the number of ticklabels. One may then adapt the margin around the axes and set the calculated size as a new figure size.

import numpy as np
import matplotlib.pyplot as plt

N = 150
data = np.linspace(0, N, N)

plt.plot(data)

plt.xticks(range(N)) # add loads of ticks
plt.grid()

plt.gca().margins(x=0)
plt.gcf().canvas.draw()
tl = plt.gca().get_xticklabels()
maxsize = max([t.get_window_extent().width for t in tl])
m = 0.2 # inch margin
s = maxsize/plt.gcf().dpi*N+2*m
margin = m/plt.gcf().get_size_inches()[0]

plt.gcf().subplots_adjust(left=margin, right=1.-margin)
plt.gcf().set_size_inches(s, plt.gcf().get_size_inches()[1])

plt.savefig(__file__+".png")
plt.show()

Sample Image

Note that if the figure shown in the plotting window is larger than the screen, it will be shrunk again, so the resized figure is only shown in its new size when saved. Or, one may choose to incorporate it in some window with scrollbars as shown in this question: Scrollbar on Matplotlib showing page

Pyplot spacing of tick labels on x axis

A part of your problem arises, because you have omitted the x coordinates in your plot functions. If you were using

plt.plot(x, np.log(x))

you would not have the spacing problem.

If you omit the x coordinate it gets replaced internaly by a np.arange(len(y)) and so your xaxis has values from 0 to 100 instead of 0 to 10.

For reference:

Sample Image
Sample Image

In general matplotlib has socalled locators to deal with tick spacings:

https://matplotlib.org/examples/ticks_and_spines/tick-locators.html

How to change axis tick label spacing on python graph?

Option 1: rotate the labels. In this way, you "gain" some space.

import matplotlib.pyplot as plt
import numpy as np

x=["Monday","Tuesday","Wednesday","Thursday","Fryday","Saturday","Sunday"]
y=np.linspace(1,100,7)

fig,ax = plt.subplots()
ax.plot(x,y)
ax.tick_params(axis='x', rotation=45)

Sample Image

Option 2: personalize your labels.

ax.plot(x,y)
ax.set_xticklabels(['M','T','W','R','F','S','N'])
fig.savefig("/Users/Alessandro/Desktop/2.png")

Sample Image

Option 3: diminish label frequency.

ax.plot(x,y)
ax.set_xticks([0,2,4,6])
ax.set_xticklabels(['M','W','F','N'])

Sample Image

Option 4: diminish ticklabel size.

ax.plot(x,y)
ax.xaxis.set_tick_params(labelsize=8)

Sample Image

Option 5: enlarge figure size.

fig,ax = plt.subplots(figsize=(8,4))

ax.plot(x,y)

Sample Image

Matplotlib: Change distance between two x-axis tick marks on plot

I have rewritten the code as closely as possible. The main problem is that you generate two axes objects - one with for xe, ye,c in zip(x, y,colors): plt.scatter([xe] * len(ye), ye, c=c) and another one with plt.axes().set_xticklabels(['Part 1','Part 2'],rotation = 45). You can provide the labels instead directly with plt.xticks():

import matplotlib.pyplot as plt

x = [1,2]
y = [[0.1, 0.6, 0.9],[0.5,0.7,0.8]]
colors = ['red', 'blue']
plt.title("Algorithm comparison - p-values")
for xe, ye,c in zip(x, y,colors):
plt.scatter([xe] * len(ye), ye, c=c)
plt.xticks([1,2], ['Part 1','Part 2'], rotation = 45)

plt.show()

Preferably, you create one axis object in the beginning and plot everything using this axis object:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
x = [1,2]
y = [[0.1, 0.6, 0.9],[0.5,0.7,0.8]]
colors = ['red', 'blue']
ax.set_title("Algorithm comparison - p-values")
for xe, ye, c in zip(x, y, colors):
ax.scatter([xe] * len(ye), ye, c=c)
ax.set_xticks(x)
ax.set_xticklabels(['Part 1','Part 2'],rotation = 45)
ax.set_xlim(0.5, 2.5)
plt.show()

Sample output:
Sample Image

For more explanations regarding differences between the object-oriented approach and the plt interface can be found here and the matplotlib documentation.

R, Change distance between axis tick marks and tick mark labels

Quick solution is to put las=2 in both your barplot() and axis() calls to make labels horizontal and they'll be clearer.

EDIT: Use mtext instead of axis:

mtext("0.95",2,.5,at=.95,las=2,cex=.75)

How do I add space between the ticklabels and the axes in matplotlib

It looks like matplotlib respects these settings as rcParams:

pylab.rcParams['xtick.major.pad']='8'
pylab.rcParams['ytick.major.pad']='8'

Set those before you create any figures and you should be fine.

I've looked at the source code and there doesn't appear to be any other way to set them programmatically. (tick.set_pad() looks like it tries to do the right thing, but the padding seems to be set when the Ticks are constructed and can't be changed after that.)



Related Topics



Leave a reply



Submit