Pandas Timeseries Plot Setting X-Axis Major and Minor Ticks and Labels

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

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

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

Setting ticks to 30 minutes on x axis in mplfinance creates too frequent ticks

I ran a test and confirmed my hypothesis (see my comment under the question) ... indeed setting kwarg show_nontrading=True in the call to mpf.plot() will allow the axlist[0].xaxis.set_major_locator(mdates.MinuteLocator(interval=30)) to work correctly.

However it may not set the ticks on exactly the 30 minute mark, rather each tick will be 30 minutes from the previous tick.

It appears that the way to set the ticks exactly on the 00 and 30 minute mark is, instead of interval=30 say byminute=[0,30], thus:

axlist[0].xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0,30]))

pandas .plot() x-axis tick frequency -- how can I show more ticks?

No need to pass any args to MonthLocator. Make sure to use x_compat in the df.plot() call per @Rotkiv's answer.

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

df = pd.DataFrame(np.random.rand(100,2), index=pd.date_range('1-1-2018', periods=100))
ax = df.plot(x_compat=True)
ax.xaxis.set_major_locator(mdates.MonthLocator())
plt.show()
  • formatted x-axis with set_major_locator

Sample Image

  • unformatted x-axis

Sample Image

Pandas time series plot - setting custom ticks

Your problem is that there are actually two kinds of tick labels involved in this: major and minor ticklabels, at major and minor ticks. You want to clear both of them. For example, if ax is the axis in question, the following will work:

ax.set_xticklabels([],minor=False) # the default
ax.set_xticklabels([],minor=True)

You can then set the ticklabels and tick locations that you want.

How to remove the first and last minor tick month labels on matplotlib?

Try setting your x-axis limit to values between 0 and 365. Sometimes matplotlib uses values a little outside of your data. This way, the first Dec and last Jan are automatically eliminated from the plot.

Here I modified your code with 1 argument: plt.xlim(0,365)

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

df = pd.DataFrame(np.random.randint(0,100,size=(365, 2)), columns=list('AB'))
df.index = pd.date_range(start='1/1/2022', end='12/31/2022').strftime('%b-%d')

plt.figure()
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.MonthLocator(bymonthday=16))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%b'))

for tick in ax.xaxis.get_minor_ticks():
tick.tick1line.set_markersize(0)
tick.tick2line.set_markersize(0)
tick.label1.set_horizontalalignment('center')

plt.xlim(0,365)
plt.plot(df['A'], linewidth=0.5, color='tab:red')

plt.show()

Sample Image

How to format minor ticks on twin x- and y- axes, both of which are logarithmically scaled?

Your minor ticks are hidden by your major ticks.

axj.set_xscale('log', basex=2)
axj.set_yscale('log', basey=2)

Set scales of your "twin axes" to logarithm, and so with logarithm major ticks (4, 16, 64, 256, 1024).

axj.xaxis.set_minor_locator(ticker.LogLocator(base=2))
axj.yaxis.set_minor_locator(ticker.LogLocator(base=2))

This, add minor ticks on logarithm locations which will be 4, 16, 64, 256, 1024 ; the same that your major ticks.

What you want to do is either:

axi.xaxis.set_minor_locator(ticker.LogLocator(base=2))
axi.yaxis.set_minor_locator(ticker.LogLocator(base=2))

Adding minor logarithm ticks to your linear axis, or:

axj.xaxis.set_minor_locator(ticker.LinearLocator())
axj.yaxis.set_minor_locator(ticker.LinearLocator())

Adding minor linear ticks to your logarithm axis.

Set the number of minor ticks in matplotlib colorbar

You can use the AutoMinorLocator to set the number of minor ticks (note that when setting n=4, one of the major ticks is counted as 1). Here is an example:

import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, ScalarFormatter
import numpy as np

data = np.random.rand(10, 10)

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))

img1 = ax1.imshow(data, cmap='inferno', aspect='auto', vmin=0, vmax=1)
cbar1 = plt.colorbar(img1, ax=ax1)
ax1.set_title('default colorbar ticks')

img2 = ax2.imshow(data, cmap='inferno', aspect='auto', vmin=0, vmax=1)
cbar2 = plt.colorbar(img2, ax=ax2)
# 3 major ticks
cbar2.ax.locator_params(nbins=3)
# 4 minor ticks, including one major, so 3 minor ticks visible
cbar2.ax.yaxis.set_minor_locator(AutoMinorLocator(n=4))
# show minor tick labels
cbar2.ax.yaxis.set_minor_formatter(ScalarFormatter())
# change the color to better distinguish them
cbar2.ax.tick_params(which='minor', color='blue', labelcolor='crimson')
ax2.set_title('3 major, 4 minor colorbar ticks')

plt.tight_layout()
plt.show()

setting minor colorbar ticks



Related Topics



Leave a reply



Submit