You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly Dash布局问题:下拉菜单无法与子图横向并排

问题分析与修复方案

你的布局换行问题主要由以下几个原因导致:

1. 子图固定宽度超出列容器范围

你给class_topic_subplot设置了固定宽度width=800,但Bootstrap的dbc.Col(width=3)对应的容器宽度远小于800px(默认12列布局中,3列仅占25%页面宽度),图的尺寸超出列的容纳范围,自然会被挤到下一行。

2. 代码存在未定义变量错误

代码中class_category_earned = students_category_earned.groupby(...)这一行,students_category_earned变量未定义,会导致程序运行报错,需要先注释或删除该行。

3. 下拉菜单被隐藏

student_selection_card里的Dropdown设置了style={'display':False},会直接隐藏下拉组件,你应该移除这个样式才能看到菜单。


修复后的完整代码

import pandas as pd 
pd.set_option('display.max_rows', None)
from dash import Dash, dcc, html
from plotly.subplots import make_subplots
from plotly import graph_objects as go
import dash_bootstrap_components as dbc

# 引入Bootstrap样式,确保布局规则正常生效
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

colors = {
    'grey_plot_bg':'#353535',
    'background': '#111111',
    'text': 'teal',
    'plottext':'crimson',
    "0":"silver",
    "1":"#FBEC5D",
    "5":"#50C878",
    "10":"#40E0D0",
    "15":"#A23D60",
    0:"silver",
    1:"#FBEC5D",
    5:"#50C878",
    10:"#40E0D0",
    15:"#A23D60",
    'Linux':'#50C878',
    'Windows':'#66D3F4',
    'Primer':'#FFD700',
}

# pandas dataframe used for plots
current_merged_df =  pd.DataFrame({
    'student': ['scooby','doobie','doo'],
    'completed' : [ 55 , 55 , 100 ]
})

students_topics_earned = pd.DataFrame({
    'topic': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','A','A','B','B','C','C'],
    'completed' : [ 55 , 55 , 100 , 95 , 45 , 99 , 75 , 64 , 93 , 10 , 15 , 55 , 45 , 78 , 98 , 33 ],
    'platform' : ['Primer','Primer','Primer','Primer','Primer','Primer','Primer','Primer', 'Primer', 'Primer','Linux','Windows','Linux','Windows','Linux','Windows']
})

# 注释未定义变量的错误代码,或补充对应数据集
# class_category_earned = students_category_earned.groupby(['platform','Category']).mean().round().reset_index()
class_topics_earned = students_topics_earned.groupby(['platform','topic']).mean().round().reset_index()

def student_topic_scatter_polar_graph(df,platform):
    df_filtered = df[df['platform']==platform].sort_values(by='topic',ascending=True)
    color = colors[platform]

    fig = go.Scatterpolar(
                    r=df_filtered.completed,
                    theta=df_filtered.topic,
                    fill='toself',
                    name=f"{platform} - Focused Topics",
                    fillcolor=color, 
                    opacity=0.6,
                    line=dict(color=color),
                    mode='markers'
    )
    return fig

# 调用绘图函数
class_linux_topic_scatter_polar_fig = student_topic_scatter_polar_graph(class_topics_earned,'Linux')
class_windows_topic_scatter_polar_fig = student_topic_scatter_polar_graph(class_topics_earned,'Windows')
class_Primer_topic_scatter_polar_fig = student_topic_scatter_polar_graph(class_topics_earned,'Primer')

class_topic_subplot =  make_subplots(rows=2, cols=2,
                    subplot_titles=['Primer','Linux','Windows'],
                    specs=[
                            [{"rowspan": 1,"colspan":2,"type": "polar"},None],
                            [ {"rowspan": 1,"type": "polar"}, {"rowspan": 1,"type": "polar"}]
                            ])

class_topic_subplot.add_trace(class_Primer_topic_scatter_polar_fig,row=1,col=1)
class_topic_subplot.add_trace(class_windows_topic_scatter_polar_fig,row=2,col=1)
class_topic_subplot.add_trace(class_linux_topic_scatter_polar_fig,row=2,col=2)

# 修改布局为自适应宽度,让图表适配列容器
class_topic_subplot.update_layout(
    autosize=True,
    height=600,
)

def populate_student_selection_dropdown(current_merged_df):
    if current_merged_df is not None:
        merged_df = pd.DataFrame.from_records(current_merged_df)
        return [s for s in merged_df['student'].unique()]

student_selection_card = dbc.Card(
    [
        html.H6("Select Individual Students for Analysis:",className="card-text"),
        # 移除隐藏样式,显示下拉菜单
        dcc.Dropdown(['scoobie','doobie','doo'],id="student_selection_dropdown",multi=True,persistence=True)
    ]
)

card2 = dbc.Card(
                    [
                        dbc.CardBody([
                            html.H4("Student Name", className="card-title"),
                            dcc.Graph(figure=class_topic_subplot),
                        ])
                    ]
                )

# 调整列宽分配为4-4-4(总12列),添加垂直居中,使用自适应容器
class_analysis_layout = dbc.Container([
    dbc.Row(
        [
            dbc.Col([card2],width=4),
            dbc.Col([student_selection_card],width=4),
            dbc.Col([card2],width=4)
        ],
        align="center"
    )
], fluid=True)

app.layout = html.Div([
        class_analysis_layout
    ])

if __name__ == '__main__':
    app.run_server(host="0.0.0.0", port=8070, debug=True)

关键修改点说明

  • 移除子图固定宽度:将class_topic_subplot.update_layout中的width=800改为autosize=True,让图表自动适配所在列的宽度。
  • 修复未定义变量:注释掉students_category_earned相关的错误代码行。
  • 显示下拉菜单:删除Dropdown的style={'display':False}配置。
  • 优化列宽与容器:使用fluid=True让容器自适应页面,调整列宽为4-4-4(总12列),并添加align="center"让内容垂直居中。
  • 引入Bootstrap样式:初始化Dash时添加external_stylesheets=[dbc.themes.BOOTSTRAP],确保Bootstrap布局样式正常生效。

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 07:05:19