Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Line Colour with Plotly Express

I have a plotly express figure:

fig = px.line(data, x="DateTime", y="Gold", title="Gold Prices")

I want to change some details, like so

fig.update_layout(
    line_color="#0000ff",  # ValueError: Invalid property specified for object of type plotly.graph_objs.Layout: 'line'
    line=dict(
        color='rgb(204, 204, 204)',
        width=5
    ),  # Bad property path: line
)

But both attempts (trying solutions I researched on here) failed, with the errors given in the comments.

I have also tried fig = px.line(data, x="DateTime", y="Gold", title="Gold Prices", template="ggplot2", color_discrete_map={"Gold": "green"}) to no avail.

How do I make this work please?

like image 207
Robin Andrews Avatar asked Sep 02 '21 07:09

Robin Andrews


People also ask

How do I change the color line in Plotly Express?

If we use plotly express, we can customize the color of a line plot using the update_traces() function. The update_traces() function allows us to add or remove features from an existing plot. This makes it easy to pass properties and values on customizing their plots.

How do you use colors in plotly?

Color Sequences in Plotly ExpressBy default, Plotly Express will use the color sequence from the active template's layout. colorway attribute, and the default active template is plotly which uses the plotly color sequence. You can choose any of the following built-in qualitative color sequences from the px. colors.

Is Plotly Express the same as plotly?

Plotly Express is a built-in part of the plotly library, and is the recommended starting point for creating most common figures. Every Plotly Express function uses graph objects internally and returns a plotly.


2 Answers

Try to use .update_traces() with plotly.express instead of .update_layout():

fig.update_traces(line_color='#0000ff', line_width=5)
like image 64
R. Marolahy Avatar answered Oct 16 '22 07:10

R. Marolahy


plotly.express

If you want to use plotly.express, add the following settings.

import plotly.express as px

df = px.data.stocks()
fig = px.line(df, x='date', y="GOOG", title='Ticker:GOOG')

fig['data'][0]['line']['color']='rgb(204, 204, 204)'
fig['data'][0]['line']['width']=5

fig.show()

plotly.graph_objects

If you are using plotly.graph_objects, you can set it in go.Scatter().

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

df = px.data.stocks()
fig = go.Figure(data=go.Scatter(x=df['date'], y=df['GOOG'], mode='lines', line_color='rgb(204, 204, 204)', line_width=5))
fig.update_layout(title='Ticker:GOOG')

fig.show()

enter image description here

like image 7
r-beginners Avatar answered Oct 16 '22 07:10

r-beginners