matplotlib中每个月的主要滴答声和每周的次要滴答声

2024-10-01 22:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一幅图,显示了一年中每一天每小时的温度

这是我写的代码:

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轴至少可以显示一些东西,而不仅仅是零,但我还没有找到如何执行我刚才描述的操作


Tags: csvdfdatetimefigplttemppd
1条回答
网友
1楼 · 发布于 2024-10-01 22:30:08

月份显示由MonthLocator设置为带有月份缩写的一个月。几周来,我们在DayLocator中有7天的间隔数据,并设置原始标签。使用ax.xaxis.set_minor_formatter('%U')本来很容易,但是

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()

enter image description here

相关问题 更多 >

    热门问题