如何缩小Plotly parallel_categories图适配长标签并调整support标签位置
Plotly平行分类图长标签截断与标签重叠解决方案
1. 扩容左右边距+压缩中间绘图区域
通过布局参数增加左右留白,同时缩小绘图区域的占比,给长标签腾出显示空间:
import plotly.express as px import pandas as pd # 假设已将关联规则数据转换为DataFrame df fig = px.parallel_categories(df, dimensions=['特征组合', '其他属性', 'support']) # 调整布局边距与绘图区域范围 fig.update_layout( margin=dict(l=220, r=180, t=50, b=50), # 按需调整左右边距数值 parallel_categories=dict( domain=dict(x=[0.18, 0.82]) # 缩小中间绘图区域的左右占比,范围0-1 ) )
2. 开启标签自动换行
给长标签开启自动换行功能,避免横向截断:
fig.update_traces( parallel_categories=dict( dimensions=[ dict( label=col, values=df[col], label_font=dict(size=10), textwrap=True ) for col in df.columns ] ) )
textwrap=True会自动将过长的标签换行显示,配合label_font可微调字号适配。
3. 调整右侧"support"标签位置
若右侧support标签与相邻维度重叠,可手动调整该维度的位置或增大维度间距:
方式一:手动指定维度位置
# 获取现有维度配置 dims = fig.data[0].parallel_categories.dimensions # 调整最后一个维度(support)的x坐标,数值越大越靠右 dims[-1]['x'] = 0.95 # 更新图表 fig.update_traces(parallel_categories=dict(dimensions=dims))
方式二:增大维度间空白
fig.update_traces(parallel_categories=dict(gap=0.25)) # 增大维度间间距,避免标签重叠
4. 手动拆分长标签(可选)
如果自动换行效果不佳,可提前在数据中插入换行符\n强制拆分:
# 以逗号为分隔符拆分长标签 df['特征组合'] = df['特征组合'].str.replace(',', ',\n')
内容的提问来源于stack exchange,提问作者otiv33
相关产品推荐
相关产品推荐

