Reputation: 189
I have this plot that shows the temperature of every hour for every day of the year
And this is the code that I wrote:
mydateparser = lambda x: datetime.strptime(x, "%Y-%m-%d")
df = pd.read_csv("Vaderdata.csv",
usecols=['Date','Time','Temp'],
parse_dates=['Date'],
date_parser=mydateparser)
pivot = pd.pivot_table(df, values='Temp',columns='Date',index='Time')
fig, ax = plt.subplots(figsize = (12,6))
clr = sns.color_palette("coolwarm", as_cmap=True)
fig = sns.heatmap(pivot, center = 0,cmap = clr )
plt.show()
As you an see the x-axis isn't very descriptive. I would like to have a major tick, with label, for every new month and a minor tick for every new week. I have found a few examples that formats the datetime to strings so that the x-axis at least shows something instead of just zeroes, but I haven't been able to find out how to do what I just described.
Upvotes: 2
Views: 4063
Reputation: 35240
The month display is set by MonthLocator to one month with the month abbreviation. For weeks, we have 7-day interval data in DayLocator and set the original labels. It would have been easy to use ax.xaxis.set_minor_formatter('%U')
, but
import pandas as pd
import numpy as np
import random
random.seed(202012)
date_rng = pd.date_range('2019/01/01', '2019/12/31', freq='1H')
temp = np.random.randint(-10,35, size=8737)
df = pd.DataFrame({'date':pd.to_datetime(date_rng),'Temp':temp})
df['Time'] = df['date'].dt.hour
df['Date'] = df['date'].dt.date
df['Week'] = df['date'].dt.week
df = df[['Date','Week','Time','Temp']]
pivot = pd.pivot_table(df, values='Temp',columns='Date',index='Time')
# week num create
weeks = df[['Date','Week']]
ww = weeks.groupby('Week').first().reset_index()
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
import seaborn as sns
fig, ax = plt.subplots(figsize = (24,6))
clr = sns.color_palette("coolwarm", as_cmap=True)
fig = sns.heatmap(pivot, center = 0,cmap = clr )
months = mdates.MonthLocator(interval=1)
months_fmt = mdates.DateFormatter('%b')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)
days = mdates.DayLocator(interval=7)
ax.xaxis.set_minor_locator(days)
ax.xaxis.set_minor_formatter(ticker.FixedFormatter(ww.Week))
# ax.xaxis.set_minor_formatter('%U') # Not displayed correctly
plt.show()
Upvotes: 7