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

如何在Plotly distplot中设置仅一条实线其余为虚线?

Plotly分布图表设置指定线条为虚线

我希望用Plotly的分布函数突出某一变量的表现,只保留该变量的线条为实线,其余设为虚线。比如下面的示例代码生成了三组数据的分布图,请问如何将Group 2和Group 3的线条设置为虚线?

import plotly.figure_factory as ff
import numpy as np

x1 = np.random.randn(200) - 1
x2 = np.random.randn(200)
x3 = np.random.randn(200) + 1

hist_data = [x1, x2, x3]

group_labels = ['Group 1', 'Group 2', 'Group 3']
colors = ['#333F44', '#37AA9C', '#94F3E4']

# 创建分布图表(仅显示正态拟合曲线)
fig = ff.create_distplot(hist_data, group_labels, show_hist=False, colors=colors, show_rug=False)
fig.show()

解决方案

你可以在生成图表对象后,遍历图表中的每个数据线条(trace),通过修改line.dash属性来设置线条样式。以下是修改后的完整代码:

import plotly.figure_factory as ff
import numpy as np

x1 = np.random.randn(200) - 1
x2 = np.random.randn(200)
x3 = np.random.randn(200) + 1

hist_data = [x1, x2, x3]
group_labels = ['Group 1', 'Group 2', 'Group 3']
colors = ['#333F44', '#37AA9C', '#94F3E4']

# 创建分布图表
fig = ff.create_distplot(hist_data, group_labels, show_hist=False, colors=colors, show_rug=False)

# 遍历所有线条:Group 1保持实线,其余设为虚线
for idx, trace in enumerate(fig.data):
    if group_labels[idx] != 'Group 1':
        # 可选虚线样式还有:'dot'(点线)、'dashdot'(点划线)
        trace.line.dash = 'dash'

fig.show()

说明

  • fig.data包含了图表中所有的线条对象,每个对象对应一组数据
  • 通过group_labels的索引匹配对应的线条,精准控制需要修改的组别
  • 可根据需求替换dash为其他虚线样式,适配不同的视觉突出需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:55:38