如何在Python Plotly中使用Plotly Express绘制多折线图?

Plotly是Python中的开源绘图库。Python用户可以使用Plotly生成不同类型的交互式基于Web的图表,包括科学图表,3D图形,统计图表,财务图表等。

在本教程中,我们将展示如何使用 Plotly 生成多个折线图。在这里,我们将使用 plotly.express 来生成图形。它包含许多方法来自定义图表并将其呈现为HTML格式。

按照以下步骤使用Plotly Express生成多折线图。

步骤 1

将 plotly.express 模块和别名导入为 px

import plotly.express as px

步骤 2

使用以下值创建数据集 -

data = {
   'year':[2019,2020,2021,2022],
   'loss':[0,1,2,3],
   'gain':[90,91,92,93],
   'profit':[100,90,95,97]
}
df = pd.DataFrame(data)

步骤 3

使用 px.line() 方法创建线图。

fig = px.line(df, x='year', y='loss')

步骤 4

使用 add_scatter() 方法生成两个散点图。

# generate scatter plot
fig.add_scatter(x=df['year'], y=df['gain'])
fig.add_scatter(x=df['year'], y=df['profit'])

创建多折线图的完整代码如下 -

 

import plotly.express as px import pandas as pd # Create a dataset data = { 'year':[2019,2020,2021,2022], 'loss':[0,1,2,3], 'gain':[90,91,92,93], 'profit':[100,90,95,97] } df = pd.DataFrame(data) # generate the line plot fig = px.line(df, x='year', y='loss') # generate scatter plot fig.add_scatter(x=df['year'], y=df['gain']) fig.add_scatter(x=df['year'], y=df['profit']) # Set the size of the plot fig.update_layout(width=716, height=350) # show the plot fig.show()

输出

它将在浏览器上显示以下输出 -

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值