I have this plot that shows the temperature of every hour for every day of the year
这是我写的代码:
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()
正如您所看到的,x 轴的描述性并不强。
我希望每个新的月份都有一个带有标签的大勾号,每个新的一周都有一个小勾号。
我找到了一些将日期时间格式化为字符串的示例,以便 x 轴至少显示一些内容而不仅仅是零,但我无法找到如何执行我刚才描述的操作。
月份显示由 MonthLocator 设置为一个月并带有月份缩写。数周以来,我们在 DayLocator 中拥有 7 天间隔的数据并设置原始标签。本来就很容易使用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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)