Issue
I am trying to plot a pandas dataframe, but I can't show the labels on the minor ticks
The dataframe is something like this:
day_of_week hour count
0 0 150
0 1 673
...
1 0 734
1 1 35
...
where day_of_week
is the day of the week (Monday, Tuesday, etc) and hour
are the hours of the day from 0 to 23.
I want to plot this quantity as a time-series and show the major ticks as mid-night and change of the next day and the minor ticks every 6 hours.
I modified a bit the dataframe and tried to plot it, this is the code:
days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"}
df["dow"] = df["day_of_week"].apply(lambda x: days.get(x))
df["axis"] = (df["dow"] + " " + df["hour"].astype(str))
fig, ax = plt.subplots()
ax.plot(time_tweets["axis"], time_tweets["count"])
ax.grid(which="major", axis="x", linestyle="-", linewidth=2)
ax.xaxis.set_major_locator(MultipleLocator(24))
ax.xaxis.set_minor_locator(MultipleLocator(6))
plt.xticks(rotation=45, minor=True, ha="right")
plt.xticks(rotation=45, minor=False, ha="right")
This doesn't plot the label on the minor ticks, everything else is fine, the major ticks and label, the minor ticks and the grid only on the major ticks.
I tried to add plt.minorticks_on()
or plt.setp(ax.get_xticklabels(minor=True), visible=True)
, but nothing label on the minor ticks.
Do you have any suggestion?
Solution
If you create fake dates, you can use DayLocator
and HourLocator
:
base = pd.to_datetime('2023-12-18') # an arbitrary Monday
offset = pd.to_timedelta(df['day_of_week'], unit='D') \
+ pd.to_timedelta(df['hour'], unit='H')
df['dti'] = base + offset
print(df)
# Output
day_of_week hour count dti
0 0 0 584 2023-12-18 00:00:00
1 0 1 63 2023-12-18 01:00:00
2 0 2 368 2023-12-18 02:00:00
3 0 3 493 2023-12-18 03:00:00
4 0 4 864 2023-12-18 04:00:00
.. ... ... ... ...
163 6 19 42 2023-12-24 19:00:00
164 6 20 960 2023-12-24 20:00:00
165 6 21 5 2023-12-24 21:00:00
166 6 22 440 2023-12-24 22:00:00
167 6 23 295 2023-12-24 23:00:00
[168 rows x 4 columns]
import matplotlib.dates as mdates
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(df['dti'], df['count'])
ax.grid(which="major", axis="x", linestyle="-", linewidth=2)
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_minor_locator(mdates.HourLocator([6, 12, 18]))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%a'))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H'))
plt.xticks(rotation=45, minor=True, ha="right")
plt.xticks(rotation=45, minor=False, ha="right")
plt.show()
Answered By - Corralien
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.