Plotly:如何为带有for循环的数据帧中的每个变量创建散点图?

2024-06-16 12:17:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助做一个for循环来创建一个散点图,显示由一个系统分组的两个变量。 我的df是:

WTG     Power    WSPD
A0201   2000     12.1
A0202   1800     9.7
A0201   1000     6.6
A0202   1150     7.8
A0203   760      5.8
A0203   1353     8.8

所以我需要的是每个涡轮机的散点图,x轴是WSPD,y轴是功率

谢谢


Tags: dffor系统功率power涡轮机wspda0203
1条回答
网友
1楼 · 发布于 2024-06-16 12:17:18

Plotly express非常适合这一点。不需要For Loop

fig = px.scatter(df, x='WSPD', y = 'Power', color = 'WTG')

enter image description here

但是如果出于某种原因For Loop更适合您,您可以使用plotly.graph_objects

fig = go.Figure()
colors = px.colors.qualitative.Plotly
for i, cat in enumerate(df['WTG'].unique()):
    dfp = df[df['WTG']==cat]
    fig.add_trace(go.Scatter(x=dfp['WSPD'], y = dfp['Power'],
                             mode = 'markers',
                             marker_color = colors[i]))
fig.show()

完整代码,plotly express:

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd

df = pd.DataFrame({'WTG': {0: 'A0201',
                          1: 'A0202',
                          2: 'A0201',
                          3: 'A0202',
                          4: 'A0203',
                          5: 'A0203'},
                     'Power': {0: 2000, 1: 1800, 2: 1000, 3: 1150, 4: 760, 5: 1353},
                     'WSPD': {0: 12.1, 1: 9.7, 2: 6.6, 3: 7.8, 4: 5.8, 5: 8.8}})

fig = px.scatter(df, x='WSPD', y = 'Power', color = 'WTG')
fig.show()

完整代码,绘图对象:

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd

df = pd.DataFrame({'WTG': {0: 'A0201',
                          1: 'A0202',
                          2: 'A0201',
                          3: 'A0202',
                          4: 'A0203',
                          5: 'A0203'},
                     'Power': {0: 2000, 1: 1800, 2: 1000, 3: 1150, 4: 760, 5: 1353},
                     'WSPD': {0: 12.1, 1: 9.7, 2: 6.6, 3: 7.8, 4: 5.8, 5: 8.8}})


fig = go.Figure()
colors = px.colors.qualitative.Plotly
for i, cat in enumerate(df['WTG'].unique()):
    dfp = df[df['WTG']==cat]
    fig.add_trace(go.Scatter(x=dfp['Power'], y = dfp['WSPD'],
                             mode = 'markers',
                             marker_color = colors[i],
                             name = cat))
fig.show()

相关问题 更多 >