首页 > 解决方案 > 使用 Plotly 在面积图上添加一条具有适当比例的线

问题描述

我有以下代码:

import pandas as pd
import plotly.express as px
fig = px.area(df, x="Decade", y="Financial_Impact", color="Disaster_Type", title="Financial Impact, World, RCP = 2.6", color_discrete_sequence=["#FDB714", "#009CA7", "#F05023"])
fig.show()

生成以下面积图:

面积图

现在我有一个变量,称为C为每十年提供一个温度 (°C)。我怎样才能添加一条线来显示C,相对于C图表右侧的比例?

以下是数据集的前五行:

df.head()

数据集

标签: pythonchartsplotlydata-visualizationplotly-python

解决方案


import plotly.express as px
from plotly.subplots import make_subplots

subfig = make_subplots(specs=[[{"secondary_y": True}]])

fig = px.area(df, x="Decade", y="Financial_Impact", color="Disaster_Type", color_discrete_sequence=["#FDB714", "#009CA7", "#F05023"])
fig2 = px.line(df, x="Decade",y=df.C)

fig2.update_traces(yaxis="y2",showlegend=True,name='Temperature')
subfig.add_traces(fig.data + fig2.data)

subfig.layout.xaxis.title="Decades"
subfig.layout.yaxis.title="Financial Impact"
subfig.layout.yaxis2.title="°C"
subfig.layout.title="Financial Impact, World, RCP = 2.6"

subfig.show()

在此处输入图像描述


推荐阅读