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

Plotly小提琴图轴方向设置问题:无法实现横竖轴反转

解决Plotly水平带箱线小提琴图的问题

你用fig.update_traces(orientation='h')没成功的核心原因是:水平小提琴图需要把数据绑定到x参数,而不是y参数,同时要指定每个小提琴对应的y轴类别。

你的原代码里还是用y=df['one']传递数据,即使设置了水平方向,Plotly也无法正确映射轴关系,所以显示异常。

修改后的代码如下:

import plotly.graph_objects as go
import pandas as pd

data = {'one': [0.517970, 0.335520, 0.179993, 0.049795, -0.056827],
        'two': [0.457973, 0.283992, 0.136433, 0.013717, -0.085876]}
df = pd.DataFrame(data)

fig = go.Figure()

fig.add_trace(go.Violin(x=df['one'],  # 把y换成x,传递数据
                        y=['one'],     # 指定该小提琴对应的y轴类别
                        name='one',
                        box_visible=True,
                        meanline_visible=True,
                        side='positive',
                        spanmode='soft',
                        line_color='#1f77b4',
                        opacity=0.6))

fig.add_trace(go.Violin(x=df['two'],  # 同样把y换成x
                        y=['two'],     # 指定y轴类别
                        name='two',
                        box_visible=True,
                        meanline_visible=True,
                        side='positive',
                        spanmode='soft',
                        line_color='#ff7f0e',
                        opacity=0.6))

fig.update_traces(orientation='h')  # 显式设置水平方向
fig.update_layout(yaxis_title='类别', xaxis_title='数值')  # 可选:添加轴标题
fig.show()

额外优化:用长格式数据更简洁

如果把数据转成Pandas长格式,代码会更简洁,也更符合Plotly的推荐用法:

import plotly.express as px
import pandas as pd

data = {'one': [0.517970, 0.335520, 0.179993, 0.049795, -0.056827],
        'two': [0.457973, 0.283992, 0.136433, 0.013717, -0.085876]}
df = pd.DataFrame(data).melt(var_name='类别', value_name='数值')

fig = px.violin(df, x='数值', y='类别', box=True, points=False, color='类别',
                color_discrete_map={'one':'#1f77b4', 'two':'#ff7f0e'},
                opacity=0.6)
fig.update_traces(meanline_visible=True, side='positive', spanmode='soft')
fig.show()

这样就能得到你想要的水平带箱线的小提琴图效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:27:43