zesla
zesla

Reputation: 11813

Plotly: How to make line charts colored by a variable using plotly.graph_objects?

I'm making a line chart below. I want to make the lines colored by a variable Continent. I know it can be done easily using plotly.express

Does anyone know how I can do that with plotly.graph_objects? I tried to add color=gapminder['Continent'], but it did not work.

Thanks a lot for help in advance.

import plotly.express as px
gapminder = px.data.gapminder()
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(x=gapminder['year'], y=gapminder['lifeExp'],
                    mode='lines+markers'))
fig.show()

Upvotes: 3

Views: 2387

Answers (1)

vestland
vestland

Reputation: 61154

Using an approach like color=gapminder['Continent'] normally applies to scatterplots where you define categories to existing points using a third variable. You're trying to make a line plot here. This means that not only will you have a color per continent, but also a line per continent. If that is in fact what you're aiming to do, here's one approach:

Plot:

enter image description here

Code:

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

# get data
df_gapminder = px.data.gapminder()

# manage data
df_gapminder_continent = df_gapminder.groupby(['continent', 'year']).mean().reset_index()
df = df_gapminder_continent.pivot(index='year', columns='continent', values = 'lifeExp')
df.tail()

# plotly setup and traces
fig = go.Figure()
for col in df.columns:
    fig.add_trace(go.Scatter(x=df.index, y=df[col].values,
                                 name = col,
                                 mode = 'lines'))
# format and show figure
fig.update_layout(height=800, width=1000)
fig.show()

Upvotes: 3

Related Questions