I am trying to fix how python plots my data.
Say
x = [0,5,9,10,15]
and
y = [0,1,2,3,4]
Then I would do:
matplotlib.pyplot.plot(x,y) matplotlib.pyplot.show()
and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
One way you can do this is to reduce the number of ticks on the x axis. You can set the ticks using ax. set_xticks() . Here you can slice the x list to set a ticks at every 2nd entry using the slice notation [::2] .
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()
Another approach is to set the axis locator:
import matplotlib.ticker as plticker loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals ax.xaxis.set_major_locator(loc)
There are several different types of locator depending upon your needs.
Here is a full example:
import matplotlib.pyplot as plt import matplotlib.ticker as plticker x = [0,5,9,10,15] y = [0,1,2,3,4] fig, ax = plt.subplots() ax.plot(x,y) loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals ax.xaxis.set_major_locator(loc) plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With