python - 如何在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()
- 我想填充趋势线下方的区域。
- 我想填充趋势线下方的区域,但仅限于 vline 的右侧(如下图所示,为我的艺术技巧道歉)
我已经尝试过提取趋势线结果并再次绘制它们,但无法填充它们。它是平滑的趋势线(frac=0.4),而不是“正常”的情节线,这一事实使其成为一项艰巨的任务。有任何想法吗?
解决方案
我想我可以通过获取趋势线绘图数据并用它绘制面积图来获得所需的输出。我不知道原因,但是设置透明度不起作用,所以我用颜色对其进行了着色。
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()
推荐阅读
- vue.js - 在 Jest 中模拟 axios 返回 axios 未定义
- java - SimpleDateFormat 给出错误的格式输出
- swift - 如何在collectionViewCell中使用动态大小的scrollView
- python - 如何在特定目录中的所有测试之前运行一次 pytest 夹具?
- operating-system - DMA 对小数据包有效吗?
- django - Django 查询集返回空“[]”
- php - 如何在php中修复特征方法冲突和重命名方法
- amazon-web-services - 为什么 Cognito 反复调用我的 Lambda 回调,有时是同时调用?
- angular - 使用嵌套 API 调用进行角度解析
- javascript - 在 typeorm 中获取 RepositoryNotFoundError 但我很确定它们已注册