Appendix L — Scatter Plot Trendlines w/ plotly

In many cases, it may be helpful to add a trendline to a chart, to help examine relationships between variables.

The scatter function in plotly is the only type of chart that supports trendlines.

To illustrate how to add trendlines, let’s revisit the previous scatter plot example:

Code
scatter_data = [
    {"income": 30_000, "life_expectancy": 65.5},
    {"income": 35_000, "life_expectancy": 62.1},
    {"income": 50_000, "life_expectancy": 66.7},
    {"income": 55_000, "life_expectancy": 71.0},
    {"income": 70_000, "life_expectancy": 72.5},
    {"income": 75_000, "life_expectancy": 77.3},
    {"income": 90_000, "life_expectancy": 82.9},
    {"income": 95_000, "life_expectancy": 80.0},
]

incomes = []
expectancies = []
for item in scatter_data:
    incomes.append(item["income"])
    expectancies.append(item["life_expectancy"])
from plotly.express import scatter

fig = scatter(x=incomes, y=expectancies, height=350,
                title="Life Expectancy by Income",
                labels={"x": "Income", "y": "Life Expectancy (years)"},
)
fig.show()

Upon viewing the chart, looks like there may be evidence of a trend.