Plotly技术问询:如何使用For Loop为DataFrame各变量创建散点图及按涡轮机分组绘制散点图
使用Plotly结合For Loop实现散点图批量生成
嗨,我来帮你搞定这两个Plotly循环绘图的需求,分两部分详细说明:
一、为DataFrame中的每个变量创建散点图
首先得明确:散点图需要X和Y轴数据,通常我们会把每个变量作为X轴,搭配一个固定的Y轴变量(比如你的目标列),或者如果是想查看每个变量随索引的分布,就用索引当X轴。下面给你两种常见场景的实现:
场景1:每个变量与固定Y列生成散点图
假设你的DataFrame有多个特征列,想分别和Power列(举个例子)生成散点图,代码如下:
import plotly.express as px import pandas as pd # 替换成你自己的DataFrame即可 df = pd.DataFrame({ 'WSPD': [12.1, 9.7, 6.6, 7.8, 5.8, 8.8], 'Power': [2000, 1800, 1000, 1150, 760, 1353], 'Temp': [25, 23, 21, 22, 20, 24], 'Humidity': [60, 55, 58, 62, 50, 57] }) # 固定Y轴为Power,遍历所有其他列作为X轴 y_col = 'Power' for x_col in df.columns.drop(y_col): fig = px.scatter(df, x=x_col, y=y_col, title=f'{x_col} vs {y_col}') fig.show()
场景2:每个变量随索引的散点图
如果想查看每个变量自身的数据分布(X轴为行索引,Y轴为变量值),可以这样写:
import plotly.express as px import pandas as pd df = pd.DataFrame({ 'WSPD': [12.1, 9.7, 6.6, 7.8, 5.8, 8.8], 'Power': [2000, 1800, 1000, 1150, 760, 1353], 'Temp': [25, 23, 21, 22, 20, 24] }) for col in df.columns: fig = px.scatter(df, x=df.index, y=col, title=f'Distribution of {col}') fig.update_xaxes(title='Index') fig.show()
二、按涡轮机(WTG)分组生成散点图
针对你给出的DataFrame,我们需要先按WTG分组,然后为每个分组单独生成X轴为WSPD、Y轴为Power的散点图。这里给你两种实现方式,选顺手的用就行:
方式1:用pandas分组+Plotly Express(简洁版)
import plotly.express as px import pandas as pd # 你的原始数据 data = { 'WTG': ['A0201', 'A0202', 'A0201', 'A0202', 'A0203', 'A0203'], 'Power': [2000, 1800, 1000, 1150, 760, 1353], 'WSPD': [12.1, 9.7, 6.6, 7.8, 5.8, 8.8] } df = pd.DataFrame(data) # 遍历每个WTG分组生成图 for wtg, group_df in df.groupby('WTG'): fig = px.scatter(group_df, x='WSPD', y='Power', title=f'Turbine {wtg}: WSPD vs Power', labels={'WSPD': 'Wind Speed (m/s)', 'Power': 'Power Output (kW)'}) # 可选:美化标记点样式 fig.update_traces(marker=dict(size=10, color='darkblue')) fig.show()
方式2:用Plotly Graph Objects(自定义控制版)
如果你需要更精细的布局控制(比如自定义主题、添加辅助线),可以用graph_objects手动构建:
import plotly.graph_objects as go import pandas as pd data = { 'WTG': ['A0201', 'A0202', 'A0201', 'A0202', 'A0203', 'A0203'], 'Power': [2000, 1800, 1000, 1150, 760, 1353], 'WSPD': [12.1, 9.7, 6.6, 7.8, 5.8, 8.8] } df = pd.DataFrame(data) for wtg, group_df in df.groupby('WTG'): fig = go.Figure() fig.add_trace(go.Scatter( x=group_df['WSPD'], y=group_df['Power'], mode='markers', name=wtg )) fig.update_layout( title=f'Turbine {wtg}: WSPD vs Power', xaxis_title='Wind Speed (m/s)', yaxis_title='Power Output (kW)', template='plotly_white' ) fig.show()
运行代码后,每个涡轮机对应的散点图会单独弹出展示,完全符合你的需求。
内容的提问来源于stack exchange,提问作者NLGenin
相关产品推荐
相关产品推荐

