首页 > 解决方案 > 如何在plotly express散点图中填写趋势线下方的区域?

问题描述

我绘制了一个带有非线性趋势线和垂直线的散点图:

import plotly.express as px
uk_age = df[df['CountryLive']=='United Kingdom']['Age'].mean()

fig = px.scatter(df, x=x, y=y, trendline="lowess", trendline_options=dict(frac=0.4), 
                 trendline_color_override="red",template='plotly_white', range_y=[0,30])
fig.add_vline(x=uk_age, annotation_text="UK", 
              annotation_position="top right", line_color="blue")
fig.show()
  1. 我想填充趋势线下方的区域。
  2. 我想填充趋势线下方的区域,但仅限于 vline 的右侧(如下图所示,为我的艺术技巧道歉)

期望的输出

我已经尝试过提取趋势线结果并再次绘制它们,但无法填充它们。它是平滑的趋势线(frac=0.4),而不是“正常”的情节线,这一事实使其成为一项艰巨的任务。有任何想法吗?

标签: pythonplotly-express

解决方案


我想我可以通过获取趋势线绘图数据并用它绘制面积图来获得所需的输出。我不知道原因,但是设置透明度不起作用,所以我用颜色对其进行了着色。

import plotly.express as px
import plotly.graph_objects as go

df = px.data.tips()
fig = px.scatter(df, 
                 x="total_bill",
                 y="tip", 
                 trendline="lowess",
                 trendline_options=dict(frac=0.1),
                 trendline_color_override='red',
                 template='plotly_white'
                )

x_pos = 9.94
x = fig.data[1]['x']
y = fig.data[1]['y']
x = [pos for pos in x if pos >= x_pos]
y = y[len(y) - len(x):]
fig.add_trace(go.Scatter(x=x, y=y, 
                         line_color='rgba(147,112,219,0.3)',
                         fillcolor='pink',
                         opacity=0.1,
                         fill='tozeroy'))

fig.add_vline(x=x_pos, annotation_text='UK',annotation_position='top right', line_color='Blue')
fig.show()

在此处输入图像描述


推荐阅读