Adam Kubalica
Adam Kubalica

Reputation: 128

How to fill in the area below trendline in plotly express scatterplot?

I've drawn a scatterplot with a non-linear trendline and a vertical line:

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. I would like to fill the area below the trendline.
  2. I would like to fill the area below the trendline, but only to the right of the vline (like on the drawing below, apologies for my art skills)

desired output

I've played around with extracting the trendline results and plotting them again, but couldn't fill them. The fact that it's a smoothened trendline(frac=0.4), not a 'normal' plot line makes it a difficult task. Any ideas?

Upvotes: 1

Views: 993

Answers (1)

r-beginners
r-beginners

Reputation: 35155

I think I can get the desired output by getting the trend line drawing data and drawing an area graph with it. I don't know the cause, but setting the transparency didn't work, so I shaded it with color.

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()

enter image description here

Upvotes: 2

Related Questions