Change Line Colour with Plotly Express - python

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?

Try to use .update_traces() with plotly.express instead of .update_layout():
fig.update_traces(line_color='#0000ff', line_width=5)

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

Have you tried simply.
fig.add_scattergl(x=xs, y=df.y, line={'color': 'black'})
Source

Try using the "set_color" function like so:
fig.set_color('b')
or
fig.set_color('g')
where g and b can also be r for the RGB color scheme.
then
fig.show()

Related

How to add a secondary Y axis to a Plotly Express bar plot?

I would like to add a second Y axis to my bar plot bellow, that is the number of citizens in integer:
this graph was made using plotly:
import plotly.express as px
fig = px.bar(df, x="country",y="pourcent_visit",color="city",barmode='group')
# fig.add_hline(y=10)
fig.show()
To my knowledge, there's no direct way to do this. But you can easily build a Plotly Express figure, grab the traces (and data structures) from there and combine them in a figure that allows multiple axes using fig = make_subplots(specs=[[{"secondary_y": True}]]). With no provided data sample, I'll use the built-in dataset px.data.tips() that I'm guessing to a large part resembles the structure of your real world dataset judging by the way you've applied the arguments in px.bar(). Details in the comments, but please don't hesitate to let me know if something is unclear.
Plot:
Complete code:
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# sample data
df = px.data.tips()
# figure setup with multiple axes
fig = make_subplots(specs=[[{"secondary_y": True}]])
# build plotly express plot
fig2 = px.bar(df, x="day", y="total_bill", color="smoker", barmode="group")
# add traces from plotly express figure to first figure
for t in fig2.select_traces():
fig.add_trace(t, secondary_y = False)
# handle data for secondary axis
df2 = df.groupby('day').agg('sum')#.reset_index()
df2 = df2.reindex(index = df['day'].unique()).reset_index()
#
fig.add_trace(go.Scatter(x = df2['day'], y = df2['size'], mode = 'lines'), secondary_y = True)
# fix layout
fig.update_layout(legend_title_text = 'smoker')
fig.show()

How to update range_color in Plotly Express?

I am using plotly express and I want to display some data:
import plotly.express as px
dfx = px.data.tips()
fig = px.scatter(dfx,
x='total_bill', y='tip',
color='size',
template='plotly_dark',
range_color=[2,4])
My goal is to update the range color after it has been defined.
I tried something like this:
fig.update_layout(range_color=[3,6])
ValueError: Invalid property specified for object of type plotly.graph_objs.Layout: 'range'
but without success.
Are you aware of what I need to write in order to update the range color values?
To change the range of the color bar, you would change the maximum and minimum values of the color axis. This is different from the description of the graph settings, which can be found in fig.layout.
import plotly.express as px
dfx = px.data.tips()
fig = px.scatter(dfx,
x='total_bill', y='tip',
color='size',
template='plotly_dark',
range_color=[2,4])
fig.update_layout(coloraxis=dict(cmax=6, cmin=3))
fig.show()
I think you need to use range_color in the px.scatter function
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df,
x="sepal_width",
y="sepal_length",
color="sepal_length",
color_continuous_scale=["red",
"green", "blue"])
fig.show()
Here is a link to the documentation plotly
You can also look here at fig.update_coloraxes
update coloraxes
Also just found this in the documentation for update_layout
fig.update_layout(colorscale=dict(...))
update colorscale

How to specify the x coordinate on a grouped bar chart on plotly?

I made a bar chart with python plotly, and I want to put a marker on a particular bar, example non-smoking females.
Does anyone know how to specify this?
I took an example from the plotly documentation, if I try to put the marker it just takes the center of the main category.
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="sex", y="total_bill",
color='smoker', barmode='group',
height=400)
#trying to set the marker
fig.add_trace(
go.Scatter(x=["Female"],
y=[1100]
))
fig.show()
inspired by this: https://community.plotly.com/t/grouped-bar-charts-with-corresponding-line-chart/19562/4
use xaxis2, work out position, have hardcoded it, but 0.15 has relationship to number of traces in bargoup and x value
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
df = px.data.tips()
fig = px.histogram(
df, x="sex", y="total_bill", color="smoker", barmode="group", height=400
)
# trying to set the marker
fig.add_trace(
go.Scatter(
x=[0.15],
y=[1100],
customdata=[["No", "Female"]],
xaxis="x2",
hovertemplate="smoker=%{customdata[0]}<br>sex=%{customdata[1]}<br>sum of total_bill=%{y}<extra></extra>",
)
)
fig.update_layout(xaxis2={"overlaying": "x", "range": [0, 1], "showticklabels": False})
fig

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

Plotly: How to set line color?

How can I set the color of a line in plotly?
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=1, subplot_titles=('Plot 1', 'Plot 2'))
# plot the first line of the first plot
fig.append_trace(go.Scatter(x=self.x_axis_pd, y=self.y_1, mode='lines+markers', name='line#1'), row=1, col=1) # this line should be #ffe476
I tried fillcolor but that I suspected doesn't work because this is a simple line.
You can add line=dict(color="#ffe476") inside your go.Scatter(...) call. Documentation here: https://plot.ly/python/reference/#scatter-line-color
#nicolaskruchten is of course right, but I'd like to throw in two other options:
line_color="#0000ff"
And:
fig['data'][0]['line']['color']="#00ff00"
Or:
fig.data[0].line.color = "#00ff00"
I particularly appreciate the flexibility of the latter option since it easily lets you set a new color for a desired line after you've built a figure using for example fig.append_trace(go.Scatter()) or fig = go.Figure(data=go.Scatter)). Below is an example using all three options.
Code 1:
import plotly.graph_objects as go
import numpy as np
t = np.linspace(0, 10, 100)
y = np.cos(t)
y2= np.sin(t)
fig = go.Figure(data=go.Scatter(x=t, y=y,mode='lines+markers', line_color='#ffe476'))
fig.add_trace(go.Scatter(x=t, y=y2,mode='lines+markers', line=dict(color="#0000ff")))
fig.show()
Plot 1:
Now you can change the colors directly if you insert the snippet below in a new cell and run it.
Code 2:
fig['data'][0]['line']['color']="#00ff00"
fig.show()
Plot 2:
fig.add_trace(
go.Scatter(
x=list(dict_val['yolo_timecost'].keys()),
y=signal.savgol_filter(list(dict_val['yolo_timecost'].values()),2653,3),
mode='lines',
name='YOLOv3实时耗时',
line=dict(
color='rgb(204, 204, 204)',
width=5
),
),
)
fig.data[0].line.color = 'rgb(204, 20, 204)'
You can use color_discrete_sequence like that
import plotly.express as px
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada',color_discrete_sequence=["#ff97ff"])
fig.show()

Categories

Resources