使用Pandas分组并通过Plotly实现两类折线图的技术问询
使用Plotly绘制两类折线图(基于给定Pandas DataFrame)
首先定义原始数据:
import pandas as pd df = pd.DataFrame({'weight':[12,11,10,14,16,13,12,15,16], 'height':[110,111,116,111,110,113,115,114, 112], 'name':['Adam', 'Steve','Mike', 'Adam', 'Adam', 'Steve', 'Mike','Mike','Steve'], 'category':[1,1,2,2,1,2,1,1,1]})
1. 按name分组绘制weight与height折线图
用Plotly Express快速实现,以数据序号作为x轴,通过color参数按name区分折线,同时展示weight和height两个指标:
import plotly.express as px # 重置索引生成数据序号作为x轴(原数据无序列字段) df_plot = df.reset_index() # 生成折线图 fig1 = px.line(df_plot, x='index', y=['weight', 'height'], color='name', title='按name分组的weight与height折线图', labels={'index': '数据序号', 'value': '数值', 'variable': '指标'}) fig1.show()
2. 按category分张子图,子图内按name绘制折线图
先获取所有唯一分类,动态生成对应数量的子图,再循环为每个子图添加对应分类下的分组折线:
import plotly.subplots as sp import plotly.graph_objects as go # 获取所有唯一的category categories = df['category'].unique() category_count = len(categories) # 创建横向排列的子图(可调整rows/cols改为纵向排列) fig2 = sp.make_subplots(rows=1, cols=category_count, subplot_titles=[f'分类 {cat}' for cat in categories]) # 循环处理每个分类 for idx, cat in enumerate(categories, start=1): # 筛选当前分类的数据并重置索引 cat_df = df[df['category'] == cat].reset_index() # 获取当前分类下的唯一name names = cat_df['name'].unique() # 为每个name添加weight和height折线 for name in names: name_df = cat_df[cat_df['name'] == name] # 添加weight折线 fig2.add_trace(go.Scatter(x=name_df['index'], y=name_df['weight'], mode='lines', name=f'{name} - 体重'), row=1, col=idx) # 添加height折线 fig2.add_trace(go.Scatter(x=name_df['index'], y=name_df['height'], mode='lines', name=f'{name} - 身高'), row=1, col=idx) # 调整整体布局 fig2.update_layout(title='按category分张子图的weight与height折线图', showlegend=True) fig2.show()
内容的提问来源于stack exchange,提问作者serdar_bay
相关产品推荐
相关产品推荐

