如何在Python中将3个独立箱线图合并为同一并排展示图表?
Combining Multiple Box Plots into a Single Side-by-Side Chart with Plotly
Got it! You're looking to merge three separate box plots (each with unique context) into one single chart where they display side by side. With Plotly, this is straightforward—you just need to add all three box traces to the same Figure instance instead of creating separate figures for each.
Here's the adjusted code to achieve this:
import plotly.graph_objects as go # Assume you have three datasets: df1, df2, df3 (each with the column you want to plot) fig = go.Figure() # Add first box plot (original "rows" trace) fig.add_trace(go.Box( y=df1['rows'], name='rows', marker=dict(color="brown", line=dict(color="black", width=1)), opacity=1 )) # Add second box plot (replace with your second dataset/column name) fig.add_trace(go.Box( y=df2['columns'], name='columns', marker=dict(color="blue", line=dict(color="black", width=1)), opacity=1 )) # Add third box plot (replace with your third dataset/column name) fig.add_trace(go.Box( y=df3['values'], name='values', marker=dict(color="green", line=dict(color="black", width=1)), opacity=1 )) # Update layout for the combined chart fig.update_layout( title="Wykres pudełkowy dotyczący podstawowych statystyk ilościowych wybranych kolumn", yaxis_title="ilość", font=dict( family="Courier New, monospace", size=11, color="#7f7f7f" ), boxmode='group' # Explicitly sets side-by-side grouping (default behavior, but clear to read) ) fig.show()
Key Details to Note:
- Single Figure Container: All box plot traces are added to one
go.Figure()object—no need to create separate figures for each plot. Plotly automatically arranges them side by side on the x-axis. - Trace Names: The
nameparameter for eachgo.Boxtrace becomes the category label on the x-axis, so make sure these are distinct (match your actual data columns/context). - Styling Flexibility: You can keep consistent styling across traces or customize colors/line settings for each plot to make them visually distinct, as shown in the example.
- Boxmode: The
boxmode='group'setting ensures plots are grouped side by side (this is Plotly's default for multiple box traces, but explicitly defining it makes your code intent clearer).
内容的提问来源于stack exchange,提问作者dingaro
相关产品推荐
相关产品推荐

