3

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

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.