
来源:https://www.python-graph-gallery.com

山脊线图,总结几组数据的分布情况。
每个组都表示为一个密度图,每个密度图相互重叠以更有效地利用空间。
import plotly.graph_objects as go
import numpy as np
import pandas as pd
# 读取数据
temp = pd.read_csv('2016-weather-data-seattle.csv')
# 数据处理, 时间格式转换
temp['year'] = pd.to_datetime(temp['Date']).dt.year
# 选择几年的数据展示即可
year_list = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
temp = temp[temp['year'].isin(year_list)]
# 绘制每年的直方图,以年和平均温度分组,并使用'count'函数进行汇总
temp = temp.groupby(['year', 'Mean_TemperatureC']).agg({'Mean_TemperatureC': 'count'}).rename(columns={'Mean_TemperatureC': 'count'}).reset_index()
# 使用Plotly绘制脊线图,每个轨迹对应于特定年份的温度分布
# 将每年的数据(温度和它们各自的计数)存储在单独的数组,并将其存储在字典中以方便检索
array_dict = {}
for year in year_list:
# 每年平均温度
array_dict[f'x_{year}'] = temp[temp['year'] == year]['Mean_TemperatureC']
# 每年温度计数
array_dict[f'y_{year}'] = temp[temp['year'] == year]['count']
array_dict[f'y_{year}'] = (array_dict[f'y_{year}'] - array_dict[f'y_{year}'].min()) \
/ (array_dict[f'y_{year}'].max() - array_dict[f'y_{year}'].min())
# 创建一个图像对象
fig = go.Figure()
for index, year in enumerate(year_list):
# 使用add_trace()绘制轨迹
fig.add_trace(go.Scatter(
x=[-20, 40], y=np.full(2, len(year_list) - index),
mode='lines',
line_color='white'))
fig.add_trace(go.Scatter(
x=array_dict[f'x_{year}'],
y=array_dict[f'y_{year}'] + (len(year_list) - index) + 0.4,
fill='tonexty',
name=f'{year}'))
# 添加文本
fig.add_annotation(
x=-20,
y=len(year_list) - index,
text=f'{year}',
showarrow=False,
yshift=10)
# 添加标题、图例、xy轴参数
fig.update_layout(
title='1950年~2010年西雅图平均温度',
showlegend=False,
xaxis=dict(title='单位: 摄氏度'),
yaxis=dict(showticklabels=False)
)
# 跳转网页显示
fig.show()

