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.
Related
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()
So I'm trying to combine two plots into one. I've made these plots with the plotly.express library rather than the plotly.graphs_objs.
Now, plotly suggests using: fig = make_subplots(rows=3, cols=1) and then append_trace or add_trace
However, this doesn't work for express objects since the append trace expects a single. trace. How can I add a express figure to a subplot? Or is this simply not possible. One option I've tried was fig.data[0] but this will only add the first line/data entry. Rn my code looks like:
double_plot = make_subplots(rows=2, cols=1, shared_xaxes=True)
histo_phases = phases_distribution(match_file_, range)
fig = px.line(match_file,
x="Minutes", y=["Communicatie", 'Gemiddelde'], color='OPPONENT')
fig.update_layout(
xaxis_title="Minuten",
yaxis_title="Communicatie per " + str(range) + "minuten",
legend_title='Tegenstander',
)
double_plot.append_trace(fig.data, row=1, col=1)
double_plot.append_trace(histo_phases.data, row=2, col=1)
Thanks in advance.
your code sample does not include creation of data frames and figures. Have simulated
it is as simple as adding each traces from figures created with plotly express to figure created with make_subplots()
for t in fig.data:
double_plot.append_trace(t, row=1, col=1)
for t in histo_phases.data:
double_plot.append_trace(t, row=2, col=1)
full code
from plotly.subplots import make_subplots
import plotly.express as px
import pandas as pd
import numpy as np
df = px.data.tips()
double_plot = make_subplots(rows=2, cols=1, shared_xaxes=True)
# histo_phases = phases_distribution(match_file_, range)
histo_phases = px.histogram(df, x="total_bill")
match_file = pd.DataFrame(
{
"Minutes": np.repeat(range(60), 10),
"Communicatie": np.random.uniform(1, 3, 600),
"Gemiddelde": np.random.uniform(3, 5, 600),
"OPPONENT": np.tile(list("ABCDEF"), 100),
}
)
fig = px.line(match_file, x="Minutes", y=["Communicatie", "Gemiddelde"], color="OPPONENT")
fig.update_layout(
xaxis_title="Minuten",
yaxis_title="Communicatie per " + str(range) + "minuten",
legend_title="Tegenstander",
)
for t in fig.data:
double_plot.append_trace(t, row=1, col=1)
for t in histo_phases.data:
double_plot.append_trace(t, row=2, col=1)
double_plot
I would like to create a subplot with 2 plot generated with the function plotly.express.line, is it possible? Given the 2 plot:
fig1 =px.line(df, x=df.index, y='average')
fig1.show()
fig2 = px.line(df, x=df.index, y='Volume')
fig2.show()
I would like to generate an unique plot formed by 2 subplot (in the example fig1 and fig2)
Yes, you can build subplots using plotly express. Either
1. directly through the arguments facet_row and facet_colums (in which case we often talk about facet plots, but they're the same thing), or
2. indirectly through "stealing" elements from figures built with plotly express and using them in a standard make_subplots() setup with fig.add_traces()
Method 1: Facet and Trellis Plots in Python
Although plotly.express supports data of both wide and long format, I often prefer building facet plots from the latter. If you have a dataset such as this:
Date variable value
0 2019-11-04 average 4
1 2019-11-04 average 2
.
.
8 2019-12-30 volume 5
9 2019-12-30 volume 2
then you can build your subplots through:
fig = px.line(df, x='Date', y = 'value', facet_row = 'variable')
Plot 1:
By default, px.line() will apply the same color to both lines, but you can easily handle that through:
fig.update_traces(line_color)
This complete snippet shows you how:
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
df = pd.DataFrame({'Date': ['2019-11-04', '2019-11-04', '2019-11-18', '2019-11-18', '2019-12-16', '2019-12-16', '2019-12-30', '2019-12-30'],
'variable':['average', 'volume', 'average', 'volume', 'average','volume','average','volume'],
'value': [4,2,6,5,6,7,5,2]})
fig = px.line(df, x='Date', y = 'value', facet_row = 'variable')
fig.update_traces(line_color = 'red', row = 2)
fig.show()
Method 2: make_subplots
Since plotly express can do some pretty amazing stuff with fairly complicated datasets, I see no reason why you should not stumple upon cases where you would like to use elements of a plotly express figure as a source for a subplot. And that is very possible.
Below is an example where I've built to plotly express figures using px.line on the px.data.stocks() dataset. Then I go on to extract some elements of interest using add_trace and go.Scatter in a For Loop to build a subplot setup. You could certainly argue that you could just as easily do this directly on the data source. But then again, as initially stated, plotly express can be an excellent data handler in itself.
Plot 2: Subplots using plotly express figures as source:
Complete code:
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
from plotly.subplots import make_subplots
df = px.data.stocks().set_index('date')
fig1 = px.line(df[['GOOG', 'AAPL']])
fig2 = px.line(df[['AMZN', 'MSFT']])
fig = make_subplots(rows=2, cols=1)
for d in fig1.data:
fig.add_trace((go.Scatter(x=d['x'], y=d['y'], name = d['name'])), row=1, col=1)
for d in fig2.data:
fig.add_trace((go.Scatter(x=d['x'], y=d['y'], name = d['name'])), row=2, col=1)
fig.show()
There is no need to use graph_objects module if you have just already generated px figures for making subplots. Here is the full code.
import plotly.express as px
import pandas as pd
from plotly.subplots import make_subplots
df = px.data.stocks().set_index('date')
fig1 = px.line(df[['GOOG', 'AAPL']])
fig2 = px.line(df[['AMZN', 'MSFT']])
fig = make_subplots(rows=2, cols=1)
fig.add_trace(fig1['data'][0], row=1, col=1)
fig.add_trace(fig1['data'][1], row=1, col=1)
fig.add_trace(fig2['data'][0], row=2, col=1)
fig.add_trace(fig2['data'][1], row=2, col=1)
fig.show()
If there are more than two variables in each plot, one can use for loop also to add the traces using fig.add_trace method.
From the documentation, Plotly express does not support arbitrary subplot capabilities. You can instead use graph objects and traces (note that go.Scatter is equivalent):
import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objects as go
## create some random data
df = pd.DataFrame(
data={'average':[1,2,3], 'Volume':[7,3,6]},
index=['a','b','c']
)
fig = make_subplots(rows=1, cols=2)
fig.add_trace(
go.Scatter(x=df.index, y=df.average, name='average'),
row=1, col=1
)
fig.add_trace(
go.Scatter(x=df.index, y=df.Volume, name='Volume'),
row=1, col=2
)
fig.show()
image of plotly chart
Hello, I'm really struggling to figure out how to format the axes on this chart. I've gone through the documentation and tried all sorts of different formatting suggestions from here and elsewhere but really not getting it. As you can see, the bottom chart has a .5 number, I want that to be skipped altogether and only have whole numbers along the axis.
I've seen ,d as a tickformat option to do this in about every answer, but I can't get that to work or I'm not seeing how to apply it to the second chart.
Can anyone with some Plotly charting experience help me out?
Here's the pertinent code:
def create_chart():
#Put data together into an interactive chart
fig.update_layout(height=500, width=800, yaxis_tickprefix = '$', hovermode='x unified', xaxis_tickformat =',d',
template=symbol_template, separators=".", title_text=(df.columns[DATA_COL_1]) + " & Units 2015-2019"
)
I believe what is happening is that the xaxis_tickformat parameter is affecting only the first subplot, but not the second one. To modify the formatting for each subplot, you can pass a dictionary with the tickformat parameter to yaxis, yaxis2, .... and so on for however many subplots you have (in your case, you only have 2 subplots).
import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objects as go
## recreate the df
df = pd.DataFrame({'Year':[2015,2016,2017,2018,2019],
'Sales':[8.8*10**7,8.2*10**7,8.5*10**7,9.1*10**7,9.6*10**7],
'Units':[36200,36500,36900,37300,37700]})
def create_chart():
#Put data together into an interactive chart
fig = make_subplots(rows=2, cols=1)
fig.add_trace(go.Scatter(
x=df.Year,
y=df.Sales,
name='Sales',
mode='lines+markers'
), row=1, col=1)
fig.add_trace(go.Scatter(
x=df.Year,
y=df.Units,
name='Units',
mode='lines+markers'
), row=2, col=1)
fig.update_layout(
title_x=0.5,
height=500,
width=800,
yaxis_tickprefix = '$',
hovermode='x unified',
xaxis_tickformat =',d',
## this will change the formatting for BOTH subplots
yaxis=dict(tickformat ='d'),
yaxis2=dict(tickformat ='d'),
# template=symbol_template,
separators=".",
title={
'text':"MCD Sales & Units 2015-2019",
'x':0.5
}
)
fig.show()
create_chart()
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()