mport pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv('data(北深).csv') df['date'] = pd.to_datetime(df['date']) # 将日期字符串转换为日期格式 df['Month'] = df['date'].dt.month # 增加一列表示月份 df['days_to_departure'] = df['days_to_departure'].astype(int) # 将天数转换为整数类型 sns.set(style='whitegrid') fig, ax = plt.subplots(figsize=(10, 10)) sns.heatmap(df.pivot_table(index='days_to_departure', columns='date', values='lowest_price'), cmap='YlOrRd', ax=ax) ax.set_title('Flight Price Heatmap') ax.set_xlabel('Date') ax.set_ylabel('Days to Departure') plt.show()上述代码生成的热力图中将横轴的日期格式改为YYYY- MM- DD的形式
时间: 2023-08-04 13:07:01 浏览: 177
js代码-import.meta 简介
可以通过在 `pivot_table` 中设置 `aggfunc` 参数为一个 lambda 函数来实现:
```python
sns.heatmap(df.pivot_table(index='days_to_departure', columns='date', values='lowest_price', aggfunc=lambda x: x), cmap='YlOrRd', ax=ax)
```
然后,可以在 `ax.set_xticklabels` 中设置日期的格式来修改横轴的日期显示格式:
```python
ax.set_xticklabels([x.strftime('%Y-%m-%d') for x in df['date'].unique()], rotation=90)
```
完整代码如下:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('data(北深).csv')
df['date'] = pd.to_datetime(df['date'])
df['Month'] = df['date'].dt.month
df['days_to_departure'] = df['days_to_departure'].astype(int)
sns.set(style='whitegrid')
fig, ax = plt.subplots(figsize=(10, 10))
sns.heatmap(df.pivot_table(index='days_to_departure', columns='date', values='lowest_price', aggfunc=lambda x: x), cmap='YlOrRd', ax=ax)
ax.set_title('Flight Price Heatmap')
ax.set_xlabel('Date')
ax.set_ylabel('Days to Departure')
ax.set_xticklabels([x.strftime('%Y-%m-%d') for x in df['date'].unique()], rotation=90)
plt.show()
```
阅读全文