Matplotlib: auto changing axis labels
I know it is possible to change the axis labels by manually setting them. (For example: Change the label label text )
However, this obviously only works if you know what labels you want, which is not the case for me.
Here is an example of what I would like to accomplish: I have two numpy arrays: x
contains numbers from 1 to 366 (but not necessarily all of them) representing the days of 2016. "Y" contains a different quantity. I would like to make a scatter plot of "y" versus "x":
import numpy as np
import matplotlib.pyplot as plt
x = np.array([27, 38, 100, 300])
y = np.array([0.5, 2.5, 1.0, 0.8])
plt.scatter(x, y)
Unsurprisingly, this creates a chart with ticks at 0, 50, 100, ..., 350. I would like to change these timestamp labels to separate dates. (For example, a mark at 50 would be labeled "Feb 19".) Suppose I have a function tick_to_date
that can convert the number 0 to a date string, so it would be easy for me to manually change all ticks in my chart. (If you need a function placeholder: tick_to_date = lambda x: ("day " + str(x))
)
ax = plt.gca()
ax.set_xticklabels([tick_to_date(tick.get_text()) for tick in ax.get_xticklabels()])
However, this is only one time. If I now zoom in or take any action that changes the ticks, the new shortcut labels won't be the way I want them.
Ideally, instead of manually setting the labels, I would say that the axis will always transform the labels of the labels by my own function tick_to_date
. Alternatively, call the above line of code every time the ticks are changed, but I'm not sure if this will work that well. Is this possible / affordable / nicely accessible?
source to share
If I really understand your question, you are looking for the formformatter from matplotlib.ticker:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker
# I added 'y' to fit second argument (position) of FuncFormatter
tick_to_date = lambda x,y: ("day " + str(x))
x = np.array([27, 38, 100, 300])
y = np.array([0.5, 2.5, 1.0, 0.8])
plt.scatter(x, y)
ax = plt.gca()
# tick_to_date will affect all tick labels through MyFormatter
myFormatter = ticker.FuncFormatter(tick_to_date)
# apply formatter for selected axis
ax.xaxis.set_major_formatter(myFormatter)
plt.show()
source to share