Is there a way to use Plotly express to show multiple subplots - python

I'm keen to know if there is an equivalent to:
import pandas as pd
import numpy as np
data = pd.DataFrame({'Day':range(10),
'Temperature': np.random.rand(10),
'Wind': np.random.rand(10),
'Humidity': np.random.rand(10),
'Pressure': np.random.rand(10)})
data.set_index('Day').plot(subplots=True, layout=(2,2), figsize=(10,5))
plt.tight_layout()
That generates Plotly graphs as opposed to matplotlib charts.

For a plotly express solution:
You could use pd.melt() to get all your variables in the same column:
import pandas as pd
import plotly.express as px
df = pd.DataFrame({
'Day':range(10),
'Temperature': np.random.rand(10),
'Wind': np.random.rand(10),
'Humidity': np.random.rand(10),
'Pressure': np.random.rand(10),})
df_melt = df.melt(
id_vars='Day',
value_vars=['Temperature', 'Wind', 'Humidity', 'Pressure'])
Your dataframe now looks like this with the variable names in a column named 'variable' and the values in a column named 'value':
Day variable value
0 0 Temperature 0.609
1 1 Temperature 0.410
2 2 Temperature 0.194
3 3 Temperature 0.663
4 4 Temperature 0.351
Now you can use px.scatter() with argument facet_col to get the multiple plots:
fig = px.scatter(
df_melt,
x='Day',
y='value',
facet_col='variable',
facet_col_wrap=2,
color='variable',
width=800,
)
This results in the following plot:
Now in your example all variables have the same range of values. But if this is not the case then you might want to make sure that every plot gets its own range on the y-axis. This can be done as follows:
fig.update_yaxes(showticklabels=True, matches=None)
More info on facet plots can be found here:
https://plotly.com/python/facet-plots/

As per the documentation, Plotly Express does not support arbitrary subplot capabilities, instead it supports faceting by a given data dimension, and it also supports marginal charts to display distribution information.
This demonstrates the usage of the lower-level plotly.subplots module and the make_subplots function it exposes to construct figures with arbitrary subplots.
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# using your sample data
fig = make_subplots(rows=2, cols=2, start_cell="bottom-left")
fig.add_trace(go.Scatter(x=data.index, y=data.Temperature, name='Temp'),
row=1, col=1, )
fig.add_trace(go.Scatter(x=data.index, y=data.Wind, name='Wind'),
row=1, col=2)
fig.add_trace(go.Scatter(x=data.index, y=data.Humidity, name='Humidity'),
row=2, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data.Pressure, name='Pressure'),
row=2, col=2)
fig.show()

I wanted simply to plot quickly multiple distribution subplots one after another like in sns, pyplot. For loop works. Works of course also with scatter. Nice touch: even the xlables are printed.
for col in boston_df.columns.tolist():
boston_dis = px.histogram(boston_df,
x=col, color_discrete_sequence=['lavenderblush'],
title='Distribution',
histnorm='probability density', template='plotly_dark',
width=400, height=300)
boston_dis.show()

Related

Python Plotly multiple charts in one single view

I want use a for cycle to call a charting function and then represent the outcome chart into a section of a multi charting pageExample single chart
expected outcome
I have a charting function (see below Charting Function Section) that i recall in a the main script with a for cycle to get several charts in sequence. Now I would like to represent all the charts, in compact size (2 columns 4 rows) in one single page. In literature I find that Subplot allows me to do so but I struggle to find the right command to represent the outcome from the charting function.
I thought something like the below in the Main Section would work but it is not
---------- Main Section ---------
import pandas as pd
import numpy as np
import plotly.graph_objs as go
from sklearn.cluster import KMeans
from plotly.subplots import make_subplots
for cont in range(8):
fig = charting_func(cont)
fig_all.add_trace(fig,
row=1, col=1
) #row and col incrementing function to be defined
fig_all.update_layout(height=600, width=800, title_text="Side By Side Subplots")
fig_all.show()
----- Charting Function ------
def charting_func(n_chrt):
# Arbitrarily 10 colors for up to 10 clusters
#colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet', 'purple','pink', 'silver']
# Create Scatter plot, assigning each point a color where
# point group = color index.
fig = btc.plot.scatter(
x=btc.index,
y="Adj Close",
color=[colors[i] for i in lists_clusters[n_chrt]],
title="k-values = {0}".format(n_chrt+2)
)
# Add horizontal lines
for cluster_avg in output[n_chrt][1:-1]:
fig.add_hline(y=cluster_avg, line_width=1, line_color="blue")
# Add a trace of the price for better clarity
fig.add_trace(go.Scatter(
x=btc.index,
y=btc['Adj Close'],
line_color="black",
line_width=1
))
# Make it pretty
layout = go.Layout(
plot_bgcolor='#D9D9D9',
showlegend=False,
# Font Families
font_family='Monospace',
font_color='#000000',
font_size=20,
xaxis=dict(
rangeslider=dict(
visible=False
))
)
fig.update_layout(layout)
return fig
type here
The basic form of a subplot is to add a location arrangement to the graph setup. So the functionalization needs to have matrix information or something like that. I have no data to present, so I have taken the stock prices of 4 companies and graphed them. As for the clustering by price, it is not included in the code, so the binning process is used to get the values and labels for the horizontal line. Please rewrite this part to your own logic. If you are good enough, the functionalization should work well.
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import itertools
import yfinance as yf
stock = ['TSLA','MSFT','AAPL','AMD']
#fig = go.Figure()
fig = make_subplots(rows=2, cols=2, subplot_titles=['MSFT','TSLA','AMD','AAPL'])
for s,rc in zip(stock, itertools.product([1,2],[2,1])):
#print(s, rc[0], rc[1])
df = yf.download(s, start="2017-09-01", end="2022-04-01", interval='1mo', progress=False)
colors = ['blue', 'red', 'green', 'purple', 'orange']
s_cut, bins = pd.cut(df['Adj Close'], 5, retbins=True, labels=colors)
fig.add_trace(go.Scatter(mode='markers+lines',
x=df.index,
y=df['Adj Close'],
marker=dict(
size=10,
color=s_cut.tolist()
)),
row=rc[0], col=rc[1]
)
for b in bins[1:-1]:
fig.add_hline(y=b, line_width=1, line_color="blue", row=rc[0], col=rc[1])
fig.update_layout(autosize=True, height=600, title_text="Side By Side Subplots")
fig.show()

Putting Linear Trendline on a Plotly Subplot

I wanted to know if there was an easier way I could put a linear regression line on a plotly subplot. The code I made below does not appear to be efficient and it makes it difficult to add annotations to the graph for the linear trendlines, which I want placed on the graph. Furthermore, it is hard to make axes and titles with this code.
I was wondering if there was a way I could create a go.Figure and somehow put it on the subplot. I have tried that, but plotly will only allow me to put the data from the figure on the subplot rather than the actual Figure, so I lose the title, axis, and trendline information. In addition, the trendline is hidden on the graphs because the scatterplot is overlaid on top of it. I tried changing how the data was displayed with data=(data[1],data[0]), but that did not work.
Basically, I want to know if there is a more efficient way of putting a trendline on the scatter plots than I pursued, so I can make it easier to set axes, set the graph size, create legends, etc, since it is difficult to work with what I coded .
sheets_dict=pd.ExcelFile('10.05.22_EMS172LabReport1.xlsx')
sheets_list=np.array(sheets_dict.sheet_names[2:])
fig=make_subplots(rows=7,cols=1)
i=0
for name in sheets_list:
df=sheets_dict.parse(name)
df.columns=df.columns.str.replace(' ','')
df=df.drop(df.index[0])
slope,y_int=np.polyfit(df.CURR1,df.VOLT1,1)
LR="Linear Fit: {:,.3e}x + {:,.3e}".format(slope,y_int)
rmse=np.sqrt(sum(slope*df.CURR1+y_int-df.VOLT1)**2)
df['Best Fit']=slope*df.CURR1+y_int
i+=1
fig.add_trace(
go.Scatter(name='Best Fit Line'+" ± {:,.3e}V".format(rmse),x=df['CURR1'],y=df['Best Fit'],
mode='lines',line_color='red',line_width=2),row=i, col=1)
fig.add_trace(
go.Scatter(name='Voltage',x=df['CURR1'],y=df['VOLT1'],mode='markers'),
row=i, col=1)
# fig.data = (fig.data[1],fig.data[0])
fig.show()
You can add titles and axes labels as follows:
import pandas as pd
import plotly.subplots as ps
fig=ps.make_subplots(rows=5,cols=1,subplot_titles=['Plot 1', 'Plot 2', 'Plot 3', 'Plot 4', 'Plot 5'])
fig.add_scatter(y=[2, 1, 3], row=1, col=1)
fig.add_scatter(y=[3, 1, 5], row=2, col=1)
fig.add_scatter(y=[2, 6, 3], row=3, col=1)
fig.add_scatter(y=[4, 0, 3], row=4, col=1)
fig.add_scatter(y=[3, 2, 3], row=5, col=1)
fig['layout']['xaxis']['title']='X-axis 1'
fig['layout']['xaxis2']['title']='X-axis 2'
fig['layout']['xaxis3']['title']='X-axis 3'
fig['layout']['xaxis4']['title']='X-axis 4'
fig['layout']['xaxis5']['title']='X-axis 5'
fig['layout']['yaxis']['title']='Y-axis 1'
fig['layout']['yaxis2']['title']='Y-axis 2'
fig['layout']['yaxis3']['title']='Y-axis 3'
fig['layout']['yaxis4']['title']='Y-axis 4'
fig['layout']['yaxis5']['title']='Y-axis 5'
fig.show()
The subplot_titles parameter in the make_subplots function is used to add plot titles. The fig['layout']['(x/y)axis(number)']['title'] is used to set the axes labels. Alternatively you can use:
fig.update_yaxes(title_text="yaxis 1 title", row=1, col=1)
or
fig.update_xaxes(title_text="xaxis 1 title", row=1, col=1)
To alter the plot sizes or spacing you can play around with the column_widths/row_heights or vertical_spacing/horizontal_spacing parameters of make_subplots:
https://plotly.com/python-api-reference/plotly.subplots.html#subplots
As for the legend, there's no direct way of associating a legend with a subplot other than what you already have but the first comment in the following link shows a way of adding an annotation on the subplot that can act sort of like a legend:
https://community.plotly.com/t/associating-subplots-legends-with-each-subplot-and-formatting-subplot-titles/33786
Trendlines are implemented in plotly.express with extensive functionality. See here. It is possible to create a subplot using that graph data, but I have created a subplot with a graph object to take advantage of your current code.
Since you did not provide specific data, I used the example data in ref. It is a data frame showing the rate of change in stock prices for several companies. It is in the form of a trend line added to it.
As for the graph, I have changed the height because a subplot requires height. The addition of axis labels for each subplot is specified in a matrix. If you need axis titles for all subplots, add them. Also, as a customization of the legend, we have grouped A group for the torrent lines and a group for the rate of change. As an example of the annotations, the slope values are set to 0 on the x-axis of each subplot and the y-axis is set to the position of the maximum value of each value.
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
df = px.data.stocks()
df.head()
date GOOG AAPL AMZN FB NFLX MSFT
0 2018-01-01 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000
1 2018-01-08 1.018172 1.011943 1.061881 0.959968 1.053526 1.015988
2 2018-01-15 1.032008 1.019771 1.053240 0.970243 1.049860 1.020524
3 2018-01-22 1.066783 0.980057 1.140676 1.016858 1.307681 1.066561
4 2018-01-29 1.008773 0.917143 1.163374 1.018357 1.273537 1.040708
from plotly.subplots import make_subplots
fig = make_subplots(rows=6,cols=1, subplot_titles=df.columns[1:].tolist())
for i,c in enumerate(df.columns[1:]):
dff = df[[c]].copy()
slope,y_int=np.polyfit(dff.index, dff[c], 1)
LR="Linear Fit: {:,.3e}x + {:,.3e}".format(slope,y_int)
rmse=np.sqrt(sum(slope*dff.index+y_int-df[c])**2)
dff['Best Fit'] = slope*df.index+y_int
fig.add_trace(go.Scatter(
name='Best Fit Line'+" ± {:,.3e}V".format(rmse),
x=dff.index,
y=dff['Best Fit'],
mode='lines',
line_color='blue',
line_width=2,
legendgroup='group1',
legendgrouptitle_text='Trendline'), row=i+1, col=1)
fig.add_trace(go.Scatter(
x=dff.index,
y=dff[c],
legendgroup='group2',
legendgrouptitle_text='Rate of change',
mode='markers+lines', name=c), row=i+1, col=1)
fig.add_annotation(x=0.1,
y=dff[c].max(),
xref='x',
yref='y',
text='{:,.3e}'.format(rmse),
showarrow=False,
yshift=5, row=i+1, col=1)
fig.update_layout(autosize=True, height=800, title_text="Stock and Trendline")
fig.update_xaxes(title_text="index", row=6, col=1)
fig.update_yaxes(title_text="Rate of change", row=3, col=1)
fig.show()

Plotting Python Plotly ECDF subplots with marginal plots

I would like to plot several plots in a subplot, specifically ecdf plots which are found under plotly express. Unfortunately I cannot get it to work because it appears subplot expects a graph objects plotly plot. The error says it receives invalid data, specifically:
"Invalid element(s) received for the 'data' property"
Obviously that means that of the following, ecdf is not included:
['bar', 'barpolar', 'box', 'candlestick',
'carpet', 'choropleth', 'choroplethmapbox',
'cone', 'contour', 'contourcarpet',
'densitymapbox', 'funnel', 'funnelarea',
'heatmap', 'heatmapgl', 'histogram',
'histogram2d', 'histogram2dcontour', 'icicle',
'image', 'indicator', 'isosurface', 'mesh3d',
'ohlc', 'parcats', 'parcoords', 'pie',
'pointcloud', 'sankey', 'scatter',
'scatter3d', 'scattercarpet', 'scattergeo',
'scattergl', 'scattermapbox', 'scatterpolar',
'scatterpolargl', 'scatterternary', 'splom',
'streamtube', 'sunburst', 'surface', 'table',
'treemap', 'violin', 'volume', 'waterfall']
Great, now, is there a work around that will allow me to plot a few of these guys next to each other?
Here's the code for a simple ecdf plot as from the documentation.
import plotly.express as px
df = px.data.tips()
fig = px.ecdf(df, x="total_bill", color="sex", markers=True, lines=False, marginal="histogram")
fig.show()
If I wanted to plot two of this same plot together for example, I would expect the following code (basically copied from the documentation) to work, probably, (if it accepted ecdf) but I cannot get it to work for the aforementioned reasons.
from plotly.subplots import make_subplots
import plotly.graph_objects as go
df = px.data.tips()
fig = make_subplots(rows=1, cols=2)
fig.add_trace(
px.ecdf(df, x="total_bill", color="sex", markers=True, lines=False, marginal="histogram"),
row=1, col=1
)
fig.add_trace(
px.ecdf(df, x="total_bill", color="sex", markers=True, lines=False, marginal="histogram"),
row=1, col=2
)
fig.update_layout(height=600, width=800, title_text="Side By Side Subplots")
fig.show()
Is there a work around for px.ecdf subplots?
Thank you in advance!
ECDF plots follow the Plotly Express pattern of having face_col parameter https://plotly.com/python-api-reference/generated/plotly.express.ecdf.html
simplest way to achieve this is to prepare the dataframe for this capability. In this example have created two copies of the data with each copy having a column for this capability
alternative is far more complex, both make_subplots() and px.ecdf() create multiple x and y axis. It would be necessary to manage all of these yourself
import plotly.express as px
import pandas as pd
df = px.data.tips()
df = pd.concat([px.data.tips().assign(col=c) for c in ["left","right"] ])
fig = px.ecdf(df, x="total_bill", color="sex", markers=True, lines=False, marginal="histogram", facet_col="col")
fig.update_layout(height=600, width=800, title_text="Side By Side Subplots")

Is it possible to create a subplot with Plotly Express?

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

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