如何在Plotly中为子图设置独立的nbinsx与nbinsy参数?
问题
使用Python的Plotly库创建包含两个子图的密度等高线图时,无法为每个子图独立设置分箱大小(nbinsx和nbinsy)。设置其中一个子图的参数会影响另一个,尝试用update_traces修改第二个子图的分箱参数也未生效。
最小可复现代码:
import plotly.graph_objs as go from plotly.subplots import make_subplots import plotly.express as px import pandas as pd # Create some dummy data df_plot = pd.DataFrame({ 'g_w1': [i for i in range(30)], 'w1_w2': [i*0.5 for i in range(30)], 'bp_g': [i*2 for i in range(30)], 'g_rp': [i*0.3 for i in range(30)], 'type': ['typeA']*15 + ['typeB']*15 }) # Create a subplot with 1 row and 2 columns fig = make_subplots(rows=1, cols=2) # First density contour plot for 'crossmatches' fig_crossmatches = px.density_contour(df_plot, x="g_w1", y="w1_w2", color='type', nbinsx=28, nbinsy=28) # Add the 'crossmatches' plot to the first subplot for trace in fig_crossmatches.data: fig.add_trace(trace, row=1, col=1) # Second density contour plot for 'no crossmatches' fig_nonmatches = px.density_contour(df_plot, x="bp_g", y="g_rp", color='type') # Add the 'no crossmatches' plot to the second subplot for trace in fig_nonmatches.data: fig.add_trace(trace, row=1, col=2) # Attempt to update the bin sizes for the second subplot fig.update_traces(selector=dict(row=1, col=2), nbinsx=128, nbinsy=128) # Update the layout if needed fig.update_layout(autosize=False, width=1500, height=600) # Show the figure fig.show()
解决方案
问题核心是:nbinsx和nbinsy是Plotly Express生成密度图时的预处理计算参数,并非已生成trace的可修改属性。trace生成后,分箱计算已完成,无法通过update_traces调整。
正确做法是在创建第二个子图的密度等高线时,直接指定目标分箱大小,而非事后修改。修改后的代码如下:
import plotly.graph_objs as go from plotly.subplots import make_subplots import plotly.express as px import pandas as pd # 创建模拟数据 df_plot = pd.DataFrame({ 'g_w1': [i for i in range(30)], 'w1_w2': [i*0.5 for i in range(30)], 'bp_g': [i*2 for i in range(30)], 'g_rp': [i*0.3 for i in range(30)], 'type': ['typeA']*15 + ['typeB']*15 }) # 创建1行2列的子图 fig = make_subplots(rows=1, cols=2) # 第一个子图:指定分箱大小 fig_crossmatches = px.density_contour(df_plot, x="g_w1", y="w1_w2", color='type', nbinsx=28, nbinsy=28) for trace in fig_crossmatches.data: fig.add_trace(trace, row=1, col=1) # 第二个子图:直接设置目标分箱大小 fig_nonmatches = px.density_contour(df_plot, x="bp_g", y="g_rp", color='type', nbinsx=128, nbinsy=128) for trace in fig_nonmatches.data: fig.add_trace(trace, row=1, col=2) # 调整布局 fig.update_layout(autosize=False, width=1500, height=600) fig.show()
关键说明
px.density_contour的nbinsx/nbinsy参数用于控制密度计算前的分箱逻辑,生成trace后这些参数不会保留为可编辑属性。- 每个子图的密度图需独立创建并指定分箱参数,再添加到对应子图位置,即可实现分箱大小的完全独立设置。
内容的提问来源于stack exchange,提问作者NeStack
相关产品推荐
相关产品推荐

