求指定Plotly_Express代码对应的Plotly Graph_Objects实现方案
Plotly Graph Objects 实现租金走势折线图方案
你可以通过遍历所有唯一区域,为每个区域单独添加go.Scatter折线迹的方式,实现和px.line完全一致的效果,具体实现如下:
首先导入所需依赖:
import plotly.graph_objects as go import pandas as pd
核心实现代码:
# 初始化画布 fig = go.Figure() # 遍历所有唯一区域,逐个添加折线 for region in Zori_filtered['RegionName'].unique(): # 筛选当前区域的所有数据 region_data = Zori_filtered[Zori_filtered['RegionName'] == region] # 添加折线 fig.add_trace( go.Scatter( x=region_data['Date'], y=region_data['Rent'], mode='lines', name=region, # 对应图例的区域名称,和px的color参数效果一致 ) ) # 可选:补充布局配置,对齐px默认生成的样式 fig.update_layout( xaxis_title='Date', yaxis_title='Rent', legend_title='RegionName' ) # 保存或展示图表 # fig.write_html("d:/downloads/zori.html") fig.show()
注意:如果你的DataFrame中存储区域名称的列名为
Region,请将上述代码中的RegionName替换为实际列名即可。
如果后续需要添加子图,只需改用make_subplots初始化画布,添加迹的时候指定对应的行列参数即可,示例如下:
from plotly.subplots import make_subplots # 初始化1行2列的子图画布 fig = make_subplots(rows=1, cols=2, subplot_titles=('租金走势', '其他指标走势')) # 第一个子图添加租金折线,指定row=1, col=1 for region in Zori_filtered['RegionName'].unique(): region_data = Zori_filtered[Zori_filtered['RegionName'] == region] fig.add_trace( go.Scatter( x=region_data['Date'], y=region_data['Rent'], mode='lines', name=region, ), row=1, col=1 ) # 第二个子图添加另一组数据,指定row=1, col=2即可 # for region in other_df['RegionName'].unique(): # region_data = other_df[other_df['RegionName'] == region] # fig.add_trace( # go.Scatter( # x=region_data['Date'], # y=region_data['其他指标'], # mode='lines', # name=region, # showlegend=False # 不需要重复显示图例可加该参数 # ), # row=1, col=2 # ) fig.update_layout(height=500, width=1200) fig.show()
内容的提问来源于stack exchange,提问作者GandalfTheWhite
相关产品推荐
相关产品推荐

