简体   繁体   中英

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

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:

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM