Plotly: How to set line color? - python

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

Related

Use one color for multiple traces added to a Figure using Plotly

I have started from the following example:
from plotly.subplots import make_subplots
from plotly import graph_objects as go
fig = make_subplots(rows=3, cols=1, subplot_titles=["foo", "bar", "goo"])
for i in range(3):
fig.add_trace(go.Box(x=list(range(100)), boxmean="sd", showlegend=False), row=i + 1, col=1)
fig.update_layout(height=600, width=1200, title_text="Yo Yo")
fig
It yields three box plots in three rows of a subplots Plotly container:
My objective is:
Get rid of the trace X strings on the left.
Use the same color for all three subplots.
By using:
fig.add_trace(go.Box(x=list(range(100)), boxmean="sd", showlegend=False, fillcolor="blue"), row=i + 1, col=1)
I'm getting closer to the second objective, but it is not yet there:
I'm guessing I can ask for a color cycle consisting of a single color; but I didn't manage to do that.
We have already tried the fill and obtained results, so I think the remaining task is to align the line colors. The y-axis labels can be set to empty by name. There are other ways to do this, but I think this is the easiest.
from plotly.subplots import make_subplots
from plotly import graph_objects as go
fig = make_subplots(rows=3, cols=1, subplot_titles=["foo", "bar", "goo"])
for i in range(3):
fig.add_trace(go.Box(x=list(range(100)),
boxmean="sd",
fillcolor='blue',
line={'color':'red'},
name='',
showlegend=False), row=i + 1, col=1)
fig.update_layout(height=600, width=1200, title_text="Yo Yo")
fig.show()

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

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

Plotly express color bar argument missing go.Bar

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x=“sepal_width”, y=“sepal_length”, color=“species”)
fig.show()
If I want to write the same code in plotly.graph_objects , than how I can include the color argument without using for loop. Basically I want to use bar and line chart in same axis with bar having a color code based on a different variable and pass that as a return in Dash.
bars =
for label, label_df in df.groupby(‘label’):
bars.append(go.Bar(x=label_df.x, y=label_df.y, name=label, marker={‘color’: colors[label]}))
trace1 = bars
trace2 = go.Scatter(x=label_df.x, y=label_df.y, name=‘Nifty 50’, mode=‘lines+markers’)
fig = go.Figure(data=[trace1])
fig.show()
You can use list comprehension:
Update:
df = px.data.iris()
trace1 = [go.Scatter(x=label_df.sepal_width,
y=label_df.sepal_length,
name=label,
mode='markers')
for label, label_df in df.groupby('species')]
fig = go.Figure(data=trace1)

Plotly:How to create subplots with python?

I am wondering what is best practice to create subplots using Python Plotly. Is it to use plotly.express or the standard plotly.graph_objects?
I'm trying to create a figure with two subplots, which are stacked bar charts. The following code doesn't work. I didn't find anything useful in the official documentation. The classic Titanic dataset was imported as train_df here.
import plotly.express as px
train_df['Survived'] = train_df['Survived'].astype('category')
fig1 = px.bar(train_df, x="Pclass", y="Age", color='Survived')
fig2 = px.bar(train_df, x="Sex", y="Age", color='Survived')
trace1 = fig1['data'][0]
trace2 = fig2['data'][0]
fig = make_subplots(rows=1, cols=2, shared_xaxes=False)
fig.add_trace(trace1, row=1, col=1)
fig.add_trace(trace2, row=1, col=2)
fig.show()
I got the following figure:
What I expect is as follows:
I'm hoping that the existing answer suits your needs, but I'd just like to note that the statement
it's not possible to subplot stakedbar (because stacked bar are in facted figures and not traces
is not entirely correct. It's possible to build a plotly subplot figure using stacked bar charts as long as you put it together correctly using add_trace() and go.Bar(). And this also answers your question regarding:
I am wondering what is best practice to create subplots using Python Plotly. Is it to use plotly.express or the standard plotly.graph_objects?
Use plotly.express ff you find a px approach that suits your needs. And like in your case where you do not find it; build your own subplots using plotly.graphobjects.
Below is an example that will show you one such possible approach using the titanic dataset. Note that the column names are noe the same as yours since there are no capital letters. The essence of this approav is that you use go.Bar() for each trace, and specify where to put those traces using the row and col arguments in go.Bar(). If you assign multiple traces to the same row and col, you will get stacked bar chart subplots if you specify barmode='stack' in fig.update_layout(). Usingpx.colors.qualitative.Plotly[i]` will let you assign colors from the standard plotly color cycle sequentially.
Plot:
Code:
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
url = "https://raw.github.com/mattdelhey/kaggle-titanic/master/Data/train.csv"
titanic = pd.read_csv(url)
#titanic.info()
train_df=titanic
train_df
# data for fig 1
df1=titanic.groupby(['sex', 'pclass'])['survived'].aggregate('mean').unstack()
# plotly setup for fig
fig = make_subplots(2,1)
fig.add_trace(go.Bar(x=df1.columns.astype('category'), y=df1.loc['female'],
name='female',
marker_color = px.colors.qualitative.Plotly[0]),
row=1, col=1)
fig.add_trace(go.Bar(x=df1.columns.astype('category'), y=df1.loc['male'],
name='male',
marker_color = px.colors.qualitative.Plotly[1]),
row=1, col=1)
# data for plot 2
age = pd.cut(titanic['age'], [0, 18, 80])
df2 = titanic.pivot_table('survived', [age], 'pclass')
groups=['(0, 18]', '(18, 80]']
fig.add_trace(go.Bar(x=df2.columns, y=df2.iloc[0],
name=groups[0],
marker_color = px.colors.qualitative.Plotly[3]),
row=2, col=1)
fig.add_trace(go.Bar(x=df2.columns, y=df2.iloc[1],
name=groups[1],
marker_color = px.colors.qualitative.Plotly[4]),
row=2, col=1)
fig.update_layout(title=dict(text='Titanic survivors by sex and age group'), barmode='stack', xaxis = dict(tickvals= df1.columns))
fig.show()
fig.show()
From what I know, it's not possible to subplot stakedbar (because stacked bar are in facted figures and not traces)...
On behalf of fig.show(), you can put to check if the html file is okay for you (The plots are unfortunately one under the other...) :
with open('p_graph.html', 'a') as f:
f.write(fig1.to_html(full_html=False, include_plotlyjs='cdn',default_height=500))
f.write(fig2.to_html(full_html=False, include_plotlyjs='cdn',default_height=500))
try the code below to check if the html file generate can be okay for you:
import pandas as pd
import plotly.graph_objects as go
#Remove the .astype('category') to easily
#train_df['Survived'] = train_df['Survived'].astype('category')
Pclass_pivot=pd.pivot_table(train_df,values='Age',index='Pclass',
columns='Survived',aggfunc=lambda x: len(x))
Sex_pivot=pd.pivot_table(train_df,values='Age',index='Sex',
columns='Survived',aggfunc=lambda x: len(x))
fig1 = go.Figure(data=[
go.Bar(name='Survived', x=Pclass_pivot.index.values, y=Pclass_pivot[1]),
go.Bar(name='NotSurvived', x=Pclass_pivot.index.values, y=Pclass_pivot[0])])
# Change the bar mode
fig1.update_layout(barmode='stack')
fig2 = go.Figure(data=[
go.Bar(name='Survived', x=Sex_pivot.index.values, y=Sex_pivot[1]),
go.Bar(name='NotSurvived', x=Sex_pivot.index.values, y=Sex_pivot[0])])
# Change the bar mode
fig2.update_layout(barmode='stack')
with open('p_graph.html', 'a') as f:
f.write(fig1.to_html(full_html=False, include_plotlyjs='cdn',default_height=500))
f.write(fig2.to_html(full_html=False, include_plotlyjs='cdn',default_height=500))
I managed to generate the subplots using the add_bar function.
Code:
from plotly.subplots import make_subplots
# plotly can only support one legend per graph at the moment.
fig = make_subplots(
rows=1, cols=2,
subplot_titles=("Pclass vs. Survived", "Sex vs. Survived")
)
fig.add_bar(
x=train_df[train_df.Survived == 0].Pclass.value_counts().index,
y=train_df[train_df.Survived == 0].Pclass.value_counts().values,
text=train_df[train_df.Survived == 0].Pclass.value_counts().values,
textposition='auto',
name='Survived = 0',
row=1, col=1
)
fig.add_bar(
x=train_df[train_df.Survived == 1].Pclass.value_counts().index,
y=train_df[train_df.Survived == 1].Pclass.value_counts().values,
text=train_df[train_df.Survived == 1].Pclass.value_counts().values,
textposition='auto',
name='Survived = 1',
row=1, col=1
)
fig.add_bar(
x=train_df[train_df.Survived == 0].Sex.value_counts().index,
y=train_df[train_df.Survived == 0].Sex.value_counts().values,
text=train_df[train_df.Survived == 0].Sex.value_counts().values,
textposition='auto',
marker_color='#636EFA',
showlegend=False,
row=1, col=2
)
fig.add_bar(
x=train_df[train_df.Survived == 1].Sex.value_counts().index,
y=train_df[train_df.Survived == 1].Sex.value_counts().values,
text=train_df[train_df.Survived == 1].Sex.value_counts().values,
textposition='auto',
marker_color='#EF553B',
showlegend=False,
row=1, col=2
)
fig.update_layout(
barmode='stack',
height=400, width=1200,
)
fig.update_xaxes(ticks="inside")
fig.update_yaxes(ticks="inside", col=1)
fig.show()
Resulting plot:
Hope this is helpful to the newbies of plotly like me.

Categories

Resources