c4mm11
c4mm11

Reputation: 49

Matplotlib: how to locate ticks and showing min and max of data

Good day,

I would like to dynamically locate my ticks and showing the min and max of the data (which is varying, thus I really can't harcode the conditions). I'm trying to use matplotlib.ticker functions and the best that I can find is MaxNLocator().. but unfortunately, it does not consider the limits of my dataset.

What would be the best approach to my problem?

Thanks!

pseudocode as follows:

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator


data1 = range(5)
ax1 = plt.subplot(2,1,1)
ax1.plot(data1)

data2 = range(63)
ax2 = plt.subplot(2,1,2)
ax2.plot(data2)

ax1.xaxis.set_major_locator(MaxNLocator(integer=True))
ax2.xaxis.set_major_locator(MaxNLocator(integer=True))

plt.show()

and the output is:

Matplotlib ticks and data limits

Upvotes: 0

Views: 3090

Answers (1)

DavidG
DavidG

Reputation: 25370

Not sure about best approach, but one possible way to do this would be to create a list of numbers between your minimum and maximum using numpy.linspace(start, stop, num). The third argument passed to this lets you control the number of points generated. You can then round these numbers using a list comprehension, and then set the ticks using ax.set_xticks().

Note: This will produce unevenly distributed ticks in some cases, which may be unavoidable in your case

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

data1 = range(5)
ax1 = plt.subplot(2,1,1)
ax1.plot(data1)

data2 = range(63)  # max of this is 62, not 63 as in the question
ax2 = plt.subplot(2,1,2)
ax2.plot(data2)

ticks1 = np.linspace(min(data1),max(data1),5)
ticks2 = np.linspace(min(data2),max(data2),5)

int_ticks1 = [round(i) for i in ticks1]
int_ticks2 = [round(i) for i in ticks2]

ax1.set_xticks(int_ticks1)
ax2.set_xticks(int_ticks2)

plt.show()

This gives:

enter image description here

Update: This will give a maximum numbers of ticks of 5, however if the data goes from say range(3) then the number of ticks will be less. I have updates the creating of int_ticks1 and int_ticks2 so that only unique values will be used to avoid repeated plotting of certain ticks if the range is small

Using the following data

data1 = range(3)
data2 = range(3063)

# below removes any duplicate ticks
int_ticks1 = list(set([int(round(i)) for i in ticks1]))
int_ticks2 = list(set([int(round(i)) for i in ticks2]))

This produces the following figure:

enter image description here

Upvotes: 1

Related Questions