I have a graph which shows the number of weeks along the x axis; how can I have 6 intermediate minor grid lines to reference the days of the week?
By default it seems to do 4 minor lines but how do I increase that?
Assuming every week starts on Monday, is it possible to label the minor lines with 'T', 'W', 'T', 'F', 'S', 'S'?
from matplotlib import pyplot
import numpy as np
# x-axis values
weeks = np.arange(0,8)
# y-axis values
cm = np.flip(np.arange(94,102))
pyplot.minorticks_on()
pyplot.grid(which='major', linestyle='-', linewidth='1', color='red')
pyplot.ylabel("cm")
pyplot.xlabel("weeks")
pyplot.plot(weeks, cm, 'go')
pyplot.grid(True, 'both')
pyplot.show()
You can use a MultipleLocator
to position the ticks at multiples of 1/7
. And a formatter that sets the correct letter depending on the fraction of 7 used.
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np
weeks = np.arange(0, 8)
cm = np.flip(np.arange(94, 102))
fig, ax = plt.subplots()
ax.plot(weeks, cm, 'go')
ax.grid(which='major', linestyle='-', linewidth='1', color='red')
ax.set_ylabel("cm")
ax.set_xlabel("weeks")
ax.minorticks_on()
ax.xaxis.set_minor_locator(MultipleLocator(1 / 7))
ax.xaxis.set_minor_formatter(lambda x, pos: 'MTWTFSS'[int(round(x * 7)) % 7])
ax.tick_params(axis='x', which='minor', labelsize=5)
ax.grid(True, which='both')
plt.show()