我正在使用 Python 中的 Plotly 创建一个包含两个子图的图形,每个子图都包含一个密度等值线图。我想为每个子图设置不同的 bin 大小(
nbinsx
和 nbinsy
)。然而,似乎为一个子图设置这些参数会影响另一个子图,而且我无法为每个子图设置独立的 bin 大小。
这是一个最小的工作示例:
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 似乎没有生效。我尝试过使用 update_traces 但无济于事。如何在 Plotly 中为每个子图设置独立的 bin 大小?
nbinsx
和nbinsy
等参数设置不会独立应用于每个子图。
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' with custom nbinsx and nbinsy
fig_crossmatches = px.density_contour(df_plot, x="g_w1", y="w1_w2", color='type', nbinsx=28, nbinsy=28)
# Add the traces from fig_crossmatches 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' with custom nbinsx and nbinsy
fig_nonmatches = px.density_contour(df_plot, x="bp_g", y="g_rp", color='type', nbinsx=128, nbinsy=128)
# Add the traces from fig_nonmatches to the second subplot
for trace in fig_nonmatches['data']:
fig.add_trace(trace, row=1, col=2)
# Update the layout
fig.update_layout(autosize=False, width=1000, height=600)
# Show the figure
fig.show()
这就是我通过修改后的示例得到的结果。绘制等高线时,第二个图中的密度看起来具有更高的箱。