import plotly.plotly as py
import plotly.graph_objs as gobj
import plotly.tools as tls
import plotly
plotly.offline.init_notebook_mode()
In order to explain how to insert into a subplot, a plot generated via a FigureFactory function, we are using the first examples posted at the links
you pointed out:
https://plot.ly/python/distplot/#plot-normal-curve
https://plot.ly/python/line-and-scatter/#scatter-with-a-color-dimension1
import numpy as np
x = np.random.randn(1000)
hist_data = [x]
group_labels = ['distplot']
fig = tls.FigureFactory.create_distplot(hist_data, group_labels)
plotly.offline.iplot(fig)
This plot consists in two subplots stacked vertically. In the upper cell is inserted the histogram and the probability density function, whereas in the lower one the rugplot.
The subplot we want to define will have two rows and two columns. In the cell (1,1) we insert the histogram+probability density function, in cell(2,1) the rugplot, and the cells (1,2) and (2,2) will be concatenated to get one cell in which we insert a Scatter plot (defined in the file at the second link you gave).
Such a structure is set via specs (subplot specifications):
my_fig = tls.make_subplots( subplot_titles=('Title1', 'Title2'),
specs=[[{}, {'rowspan': 2}], #rowspan=2 means that we concatenate (1,2) with (2,2) into one cell encoded (1,2)
[{}, None]],
rows=2,
cols=2
)
This is the format of your plot grid: [ (1,1) x1,y1 ] [ (1,2) x2,y2 ] [ (2,1) x3,y3 ] |
Define the trace to be inserted in (1,2):
right_trace = gobj.Scatter(
y = np.random.randn(500),
mode='markers',
marker=dict(
size='16',
color = np.random.randn(500), #set color equal to a variable
colorscale='Viridis',
showscale=False,
)
)
We retrieve data related to distplot from the list fig['data']
:
distplot=fig['data']
Inspect the type of each trace in distplot, in order to insert them in the right cell of our subplot:
for item in distplot:
print item['type']
histogram scatter scatter
Since each trace in the distplot is referenced to some xaxis, yaxis, via FF.create_distplot, we delete the corresponding keys, because we assign these traces to other axes in our subplots.
for item in distplot:
item.pop('xaxis', None)
item.pop('yaxis', None)
Now we append each trace to the corresponding cell:
my_fig.append_trace(distplot[0], 1, 1)
my_fig.append_trace(distplot[1], 1, 1)
my_fig.append_trace(distplot[2], 2, 1)
my_fig.append_trace(right_trace, 1, 2)
plotly.offline.iplot(my_fig)
We can improve the figure aesthtetics updating the layout of my_fig
:
my_fig['layout'].update(width=800, height=400, bargap=0.01)
my_fig['layout'].update({'xaxis2' : {'zeroline': False}})
my_fig['layout'].update({'yaxis2' : {'zeroline': False}})
plotly.offline.iplot(my_fig)
from IPython.core.display import HTML
def css_styling():
styles = open("./custom.css", "r").read()
return HTML(styles)
css_styling()