Skip to content Skip to sidebar Skip to footer

Matplotlib: How To Increase Space Between Tickmarks (or Reduce Number Of Tickmarks)?

How do you increase the spacing between the tickmarks like in the plot below? Plot 1: Setup Dataset time value 2010-01 1 2010-02 2 2010-03 3 2010-04 4 2010-05 5 2010-06 6 2010-07

Solution 1:

The tickspacing is solemnly determined by the difference of subsequent tick locations. Matplotlib will usually find nice tick locations for you automatically.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
                   "value" : np.random.randint(0,10,size=24)})
fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")

plt.show()

enter image description here

If you don't like those you may supply custom ones, via a ticker.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np

df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
                   "value" : np.random.randint(0,10,size=24)})
fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
ax.xaxis.set_major_locator(mdates.MonthLocator((1,7)))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%b"))
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")

plt.show()

enter image description here

If you really want your dates to be categorical, you may use a MultipleLocator. E.g. to tick every 5th category,

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import pandas as pd
import numpy as np

df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
                   "value" : np.random.randint(0,10,size=24)})
df["time"] = df["time"].dt.strftime('%Y-%m')

fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
ax.xaxis.set_major_locator(mticker.MultipleLocator(5))
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")

plt.show()

enter image description here


Post a Comment for "Matplotlib: How To Increase Space Between Tickmarks (or Reduce Number Of Tickmarks)?"