I am trying to plot some time dependent data in a polar coordinates system. The problem is that I got such an output that I have no clue where to start: times, locators, … not “correctly” drawn.
I need some major ticks each 2 hours, minor tick every hour, and a day label in correspondence with a day transition. In normal coordinates it seems ok but when switching to polar it seems more complicated and this is very confusing. I miss smt but don’t know what.
I have tried with
p_locator = mpolar.ThetaLocator(mdates.AutoDateLocator(minticks=24, maxticks=24))
p_formatter = mpolar.ThetaFormatter()
or with
p_locator = mdates.AutoDateLocator()
p_formatter = mdates.DateFormatter("%H:%M")
but no success. I think I missed how matplotlib works internally with datetimeobjects. Not just the ticks, locator and co. are "wrong" but the data don't even fit the full circle (-> should I apply a scale transformation?)
I would really appreciate some help to understand the mechanism behind it.
Update the axis with
ax.set_xticks(time_ticks)
ax.xaxis.set_major_formatter(p_formatter)
ax.xaxis.set_major_locator(p_locator)
Here a code sample
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
import matplotlib.projections.polar as mpolar
import matplotlib.ticker as mticker
import datetime
import random
N_MAJOR_TICKS = 12 # amount of major ticks
IS_MULTI_DAYS = True
def random_daily_hours(n_times, base_date=datetime.datetime.today()): # ordered list of day-hours
secs = sorted([random.randint(0, 24*60*60 - 1) for _ in range(n_times)])
return [base_date + datetime.timedelta(seconds=s) for s in secs]
def uniform_daily_hours(n, base_date=datetime.datetime.today()): # return floats! matplolib format!!!
return [base_date + datetime.timedelta(days=1)*i/n for i in range(n)]
# time ticks
time_ticks = uniform_daily_hours(N_MAJOR_TICKS)
# random values
random.seed(10) # fixing random state for reproducibility
x = random_daily_hours(15)
y = [random.random() for _ in range(len(x))]
# multi days - append a consecutive day
if IS_MULTI_DAYS:
day = datetime.timedelta(days=1)
x += random_daily_hours(15, base_date=datetime.datetime.today() + 1 * day)
y = [random.random() for _ in range(len(x))]
ax = plt.subplot(projection='polar')
# fix scale & orientation
ax.set_rticks([0.5, 1, 1.5, 2]) # set values radial ticks
ax.set_rlabel_position(120) # set location radial scale
ax.set_theta_zero_location('N') # set polar reference direction
ax.set_theta_direction(-1) # set default orientation - clockwise
# attempt 1
ax.set_xticks(np.linspace(0, 2 * np.pi, N_MAJOR_TICKS, endpoint=False))
ax.set_xticklabels(time_ticks)
ax.plot(x, y, '-')
ax.grid(True)
plt.show()