How to make a plotly graph wider and higher? [duplicate] - python

I have made a scatter plot using matplotlib and Plotly. I want the height, width and the markers to be scatter as in matplotlib plot. Please see the attached plots.
I used the following code in Plotly
import plotly
import plotly.plotly as py
from plotly.graph_objs import Scatter
import plotly.graph_objs as go
trace1 = go.Scatter(
x=x1_tsne, # x-coordinates of trace
y=y1_tsne, # y-coordinates of trace
mode='markers ', # scatter mode (more in UG section 1)
text = label3,
opacity = 1,
textposition='top center',
marker = dict(size = 25, color = color_4, symbol = marker_list_2, line=dict(width=0.5)),
textfont=dict(
color='black',
size=18, #can change the size of font here
family='Times New Roman'
)
)
layout = {
'xaxis': {
'showticklabels': False,
'showgrid': False,
'zeroline': False,
'linecolor':'black',
'linewidth':2,
'mirror':True,
'autorange':False,
'range':[-40, 40][![enter image description here][1]][1]
},
'yaxis': {
'showticklabels': False,
'showgrid': False,
'zeroline': False,
'linecolor':'black',
'linewidth':2,
'mirror':True,
'autorange':False,
'range':[-40, 40]
}
}
data = [trace1]
fig = go.Figure(
data= data,
layout= layout)
py.iplot(fig)
I try to tune the range but did not help. In addition, I use Autorange that did not help. Could you please help me with this.
I want the image as
##update: This can be done by the following code. I am updating this in the question:
trace1 = go.Scatter(
x=x1_tsne, # x-coordinates of trace
y=y1_tsne, # y-coordinates of trace
mode='markers +text ', # scatter mode (more in UG section 1)
text = label3,
opacity = 1,
textposition='top center',
marker = dict(size = 25, color = color_4, symbol = marker_list_2, line=dict(width=0.5)),
textfont=dict(
color='black',
size=18, #can change the size of font here
family='Times New Roman'
)
)
data = [trace1]
layout = go.Layout(
autosize=False,
width=1000,
height=1000,
xaxis= go.layout.XAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
yaxis= go.layout.YAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
margin=go.layout.Margin(
l=50,
r=50,
b=100,
t=100,
pad = 4
)
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='size-margins')

Have you considered to use
fig.update_layout(
autosize=False,
width=800,
height=800,)
and eventually reduce the size of your marker?
UPDATE
Full Code
import plotly.graph_objs as go
trace1 = go.Scatter(
x=x1_tsne, # x-coordinates of trace
y=y1_tsne, # y-coordinates of trace
mode='markers +text ', # scatter mode (more in UG section 1)
text = label3,
opacity = 1,
textposition='top center',
marker = dict(size = 12, color = color_4, symbol = marker_list_2, line=dict(width=0.5)),
textfont=dict(
color='black',
size=18, #can change the size of font here
family='Times New Roman'
)
)
data = [trace1]
layout = go.Layout(
autosize=False,
width=1000,
height=1000,
xaxis= go.layout.XAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
yaxis= go.layout.YAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
margin=go.layout.Margin(
l=50,
r=50,
b=100,
t=100,
pad = 4
)
)
fig = go.Figure(data=data, layout=layout)

Related

Setting longitude and latitude range for mapbox map

I am trying to mark some points on a map. But I would like to zoom in automatically. So I use the following code which works perfectly fine for go.Scattergeo plot.
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
margin = 0.002
fig.update_layout(
title = 'Something',
autosize=False,
width=800,
height=600,
geo = dict(
# projection_scale=8000, #this is kind of like zoom
lonaxis = dict(
range= [ df['longitude'].min()-margin, df['longitude'].max()+margin ],
dtick = 5
),
lataxis = dict (
range= [ df['latitude'].min()-margin, df['latitude'].max()+margin ],
dtick = 5
)
)
)
But when change the plot to mapbox, the lataxis and lonaxis seem not working anymore.
# fig = px.scatter_mapbox(df,
# lat="latitude",
# lon="longitude",
# color="rssi",
# color_continuous_scale=px.colors.cyclical.IceFire)
fig = go.Figure(go.Scattermapbox(
lon = df['longitude'],
lat = df['latitude'],
mode = 'markers',
marker = dict(
autocolorscale = False,
colorscale = 'icefire',
color = df['rssi'],
)))
fig.update_layout(mapbox_style="open-street-map")
Any idea how can make it work? Or how can zoom in and center graph? Any help is appreciated.

Plotly add border to a specific subplot

So I need to draw a graph with two subplots, and want to add borders to the one above. I am using plotly, but failed to find a way to do so. The borders here are essentially the solid line along the axes, but as a rectangle. Does anyone know how to add borders (axes) to a specific subplot?
My code:
#random generate points#
x1=np.random.normal(50, 10, 1000)
x2=np.random.normal(30, 10, 1000)
x3=np.random.normal(70, 10, 1000)
x1_kde=gaussian_kde(x1)
x1_range=linspace(min(x1), max(x1),len(x1))
x1_evaluated=x1_kde.evaluate(x1_range)
x2_kde=gaussian_kde(x2)
x2_range=linspace(min(x2), max(x2),len(x2))
x2_evaluated=x2_kde.evaluate(x2_range)
x3_kde=gaussian_kde(x3)
x3_range=linspace(min(x3), max(x3),len(x3))
x3_evaluated=x3_kde.evaluate(x3_range)
def bedslistmaker(x,n):
listofbeds = [x] * n
return listofbeds
x1_beds=bedslistmaker('bed 1',len(x1))
x2_beds=bedslistmaker('bed 2',len(x2))
x3_beds=bedslistmaker('bed 3',len(x3))
First three traces for the histogram (KDE)
trace1 = go.Scatter(x=x1_range,y=x1_evaluated,xaxis="x2", yaxis="y2", \
mode='lines',line={'color': '#377e22','width': 1},marker={'color':'#377e22'},\
fill='tozeroy',fillcolor='rgba(55, 126, 34, 0.25)',showlegend=True,name='x1')
trace2 = go.Scatter(x=x2_range,y=x2_evaluated,xaxis="x2", yaxis="y2", \
mode='lines',line={'color': '#0480A6','width': 1},marker={'color':'#0480A6'},\
fill='tozeroy',fillcolor='rgba(4, 128, 166, 0.25)',showlegend=True,name='x2')
trace3 = go.Scatter(x=x3_range,y=x3_evaluated,xaxis="x2", yaxis="y2", \
mode='lines',line={'color': '#FF0000','width': 1},marker={'color':'#FF0000'},\
fill='tozeroy',fillcolor='rgba(255, 0, 0, 0.25)',showlegend=True,name='x3')
Last three for the sticks below
trace4=go.Scatter(x=x1,y=x1_beds,mode="markers",xaxis= "x1", yaxis= "y1",marker={
"color": "#377e22",
"symbol": "line-ns-open"},
text=None,
showlegend=False)
trace5=go.Scatter(x=x2,y=x2_beds,mode="markers",xaxis= "x1", yaxis= "y1",marker={
"color": "#0480A6",
"symbol": "line-ns-open"
}, text=None,showlegend=False)
trace6=go.Scatter(x=x3,y=x3_beds,mode="markers",xaxis= "x1", yaxis= "y1",marker={
"color": "#FF0000",
"symbol": "line-ns-open"
}, text=None,showlegend=False)
data=[trace1,trace2,trace3,trace4,trace5,trace6]
layouts
layout = go.Layout(
xaxis1=go.layout.XAxis(
domain=[0.00, 1],
anchor="x1",
showticklabels=False),
yaxis1=go.layout.YAxis(
domain=[0.01, 0.17],
anchor="y1",
showticklabels=False,
title=go.layout.yaxis.Title(
font=dict(
family='Courier New, monospace',
size=15,
color='#7f7f7f'))),
yaxis2=go.layout.YAxis(
domain=[0.17, 1],
anchor="y2",
showticklabels=True,
title=go.layout.yaxis.Title(
text='Probability Density',
font=dict(
family='Courier New, monospace',
size=15,
color='#7f7f7f'))),
)
fig=go.Figure(data=data,layout=layout)
#fig.layout.update(showlegend=False)
fig.layout.update(template='plotly_white')#barmode='overlay'
fig.update_layout(
legend=go.layout.Legend(
x=0.73,
y=0.97,
traceorder="normal",
font=dict(
family="Courier New,monospace",
size=10,
color="#7f7f7f"
),
#bgcolor="white",
bordercolor="black",
borderwidth=1
)
)
fig.update_layout(
margin=dict(l=80, r=80, t=50, b=80))
fig.layout.update(template='plotly_white')#barmode='overlay'
fig.update_layout(autosize=False,width=1000,height=618)
fig.show()
You can set axis lines with so called mirrors for any subplot by referencing their position with row, col like this:
fig.update_xaxes(showline = True, linecolor = 'black', linewidth = 1, row = 1, col = 1, mirror = True)
fig.update_yaxes(showline = True, linecolor = 'black', linewidth = 1, row = 1, col = 1, mirror = True)
Plot:
Code:
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=2, cols=1)
fig.append_trace(go.Scatter(
x=[3, 4, 5],
y=[1000, 1100, 1200],
), row=1, col=1)
fig.append_trace(go.Scatter(
x=[2, 3, 4],
y=[100, 110, 120],
), row=2, col=1)
fig.update_xaxes(showline = True, linecolor = 'black', linewidth = 1, row = 1, col = 1, mirror = True)
fig.update_yaxes(showline = True, linecolor = 'black', linewidth = 1, row = 1, col = 1, mirror = True)
fig.update_layout(height=600, width=600, title_text="Border for upper subplot")
f = fig.full_figure_for_development(warn=False)
fig.show()

Color specific points in a plotly express strip plot

Let's take this sample dataframe :
import random
df=pd.DataFrame({'Id':list(range(1,101)), 'Value':[random.randint(0,50) for i in range(100)]})
I would like to create a plotly express strip plot in which id 5 and 10 are colored in red and the others in blue. I built the following function :
import plotly.express as px
def strip_plotly(df,col_value,col_hover=[],col_color=None,L_color=[]):
if col_color is not None :
L_color = ["red" if i in L_color else "blue" for i in df[col_color].values]
else :
L_color = ["blue"]*len(df.index)
fig = px.strip(df, y=col_value,hover_data = col_hover,color_discrete_sequence = L_color)
fig.update_layout({
'plot_bgcolor': 'rgba(0,0,0,0)',
'paper_bgcolor': 'rgba(0,0,0,0)',
},
hoverlabel=dict(
#bgcolor="white",
font_size=12,
#font_family="Rockwell"
),
xaxis={
'title':"x",
#'type':'log'
},
yaxis={'title':"y"},
title={
'text': "strip plot for stackoverflow",
#'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top'}
)
fig.update_xaxes(showspikes=True, spikecolor = 'black', showline=True, linewidth=1,linecolor='black',
ticks = "outside", tickwidth = 1, tickcolor = 'black',ticklen = 5)
fig.update_yaxes(showspikes=True, spikecolor = 'black', showline=True, linewidth=1,linecolor='black',
ticks = "outside", tickwidth = 1, tickcolor = 'black',ticklen = 5)
fig.show()
But when I run the function :
strip_plotly(df,"Value",col_hover=["Id"],col_color="Id",L_color=[5,10])
I get only blue points (ids 5 and 10 are not red). Would you please explain me what's wrong ?
have reduced size of data frame just to make it clear red points are there...
you need two traces as color is only one per trace https://plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.box.marker.html
to make traces line up have also defined offsetgroup
import random
import plotly.express as px
import numpy as np
import pandas as pd
df=pd.DataFrame({'Id':list(range(1,21)), 'Value':[random.randint(0,50) for i in range(20)]})
def strip_plotly(df,col_value,col_hover=[],col_color=None,L_color=[]):
L_color = np.where(df["Id"].isin([5,10]), "red", "blue")
# need two traces as color is in marker https://plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.box.marker.html
fig = px.strip(df.loc[L_color=="blue"], y=col_value,hover_data = col_hover,color_discrete_sequence = ["blue"])
fig = fig.add_traces(px.strip(df.loc[L_color=="red"], y=col_value,hover_data = col_hover,color_discrete_sequence = ["red"]).data)
fig = fig.update_traces(offsetgroup="1")
fig.update_layout({
'plot_bgcolor': 'rgba(0,0,0,0)',
'paper_bgcolor': 'rgba(0,0,0,0)',
},
hoverlabel=dict(
#bgcolor="white",
font_size=12,
#font_family="Rockwell"
),
xaxis={
'title':"x",
#'type':'log'
},
yaxis={'title':"y"},
title={
'text': "strip plot for stackoverflow",
#'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top'}
)
fig.update_xaxes(showspikes=True, spikecolor = 'black', showline=True, linewidth=1,linecolor='black',
ticks = "outside", tickwidth = 1, tickcolor = 'black',ticklen = 5)
fig.update_yaxes(showspikes=True, spikecolor = 'black', showline=True, linewidth=1,linecolor='black',
ticks = "outside", tickwidth = 1, tickcolor = 'black',ticklen = 5)
return fig.show()
strip_plotly(df,"Value",col_hover=["Id"],col_color="Id",L_color=[5,10])
Here's a much simpler solution.
Create a 'color' column with the desired color
Assign colors based on the values of that column (creates a separate trace for each color)
Overlay traces on top of each other
df=pd.DataFrame({'Id':list(range(1,101)), 'Value':[random.randint(0,50) for i in range(100)]})
df['color'] = np.where(df['Id'].isin([5,10]), 'red', 'blue')
fig = px.strip(df, y='Value', color='color')
fig.update_traces(offsetgroup=0)
fig.show()

Python plotly - add horizontal line to legend

I would like to add a horizontal line to the below charts so it will appear in the legend as well.
The goal is to allow to make the line appear\disappear per user choice by clicking on the legend.
Any ideas?
import plotly.graph_objects as go
tips = px.data.tips()
fig = make_subplots(rows=2, cols=2, shared_xaxes=False, vertical_spacing=0.3,horizontal_spacing=0.05)
#Scatter plot
fig.append_trace(go.Scatter(
x=tips['total_bill'],
y=tips['tip'],
mode = 'markers',
marker=dict( size=7),
showlegend = True),
row=1, col=1)
#Box plot
fig.add_trace(go.Box(
y=tips['tip'],
x = tips['sex'],
boxpoints='all',jitter=0.5,whiskerwidth=0.2,marker_size=5,line_width=2),
row=1, col=2)
#Add horizontal lines
shapes = [
{'type': 'line','x0': 5,'y0': 5,
'x1': 50,'y1' : 5,'xref': 'x1',
'yref': 'y1','line': {'color': 'red','width': 4, 'dash':'dashdot'}},
{'type': 'line','x0': 'Female','y0': 5,
'x1': 'Male','y1' : 5,'xref': 'x2',
'yref': 'y2','line': {'color': 'red','width': 4, 'dash':'dashdot'}},
]
fig['layout'].update(shapes=shapes)
fig.show()
Store all your traces in a list. Then add each of your plots to the list.
fig = go.Figure()
data = []
data.append(go.Scatter(
x=tips['total_bill'],
y=tips['tip'],
mode = 'markers',
marker=dict( size=7))
data.append(
go.Scatter(
x=(5,5),
y=(50,5),
mode='lines',
name='trace 0',
yaxis='y1'
))
layout = go.Layout(title='Some Title',showlegend=True)
fig = go.Figure(data=data, layout=layout)
fig.show()

Plotly legend next to each subplot, Python

After noticing that there was no answer to this question at the moment, I would like to know if anyone has an idea how to:
Have a legends for each subplot.
Group legends by name. (Ex: for different subplots, all have the same two curves but with different values).
Here's my Plotly script:
from plotly import tools
import plotly.plotly as py
import plotly.graph_objs as go
import plotly
nom_plot=[]
trace1 = go.Scatter(x=[1, 2, 3], y=[4, 5, 6],name='1',showlegend=True)
nom_plot.append('GRAPH 1')
trace2 = go.Scatter(x=[20, 30, 40], y=[50, 60, 70],name='2',yaxis='y2')
nom_plot.append('GRAPH 2')
trace3 = go.Scatter(x=[300, 400, 500], y=[600, 700, 800],showlegend=False)
nom_plot.append('GRAPH 3')
trace4 = go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000])
nom_plot.append('GRAPH 4')
trace5 = go.Scatter(x=[20, 30, 40], y=[50, 60, 70])
nom_plot.append('GRAPH 5')
print(trace1)
fig = tools.make_subplots(rows=4, cols=2, subplot_titles=(nom_plot))
fig.append_trace(trace1, 1, 1)
fig['layout']['xaxis1'].update(title='xaxis 1 title')
fig.append_trace(trace2, 1, 1)
fig.append_trace(trace3, 2, 1)
fig.append_trace(trace4, 2, 2)
fig['layout']['yaxis3'].update(title='yaxis 3 title')
fig.append_trace(trace5, 3, 1)
fig['layout']['yaxis2'].update(
overlaying='y1',
side='right',
anchor='x1',
# domain=[0.15, 1],
range=[2, 6],
# zeroline=False,
showline=True,
showgrid=False,
title='yaxis 3 title'
)
fig['layout'].update(height=1000, width=1000, title='Multiple Subplots' +' with Titles')
plotly.offline.plot(fig, filename='multiple-y-subplots6.html')
This what I obtain (Using Plotly Script above):
And this is what I want (Made by Pygal):
The solution is to create an HTML file that merge sevral charts offline rendered as html files:
import plotly
import plotly.offline as py
import plotly.graph_objs as go
fichier_html_graphs=open("DASHBOARD.html",'w')
fichier_html_graphs.write("<html><head></head><body>"+"\n")
i=0
while 1:
if i<=40:
i=i+1
#______________________________--Plotly--______________________________________
color1 = '#00bfff'
color2 = '#ff4000'
trace1 = go.Bar(
x = ['2017-09-25','2017-09-26','2017-09-27','2017-09-28','2017-09-29','2017-09-30','2017-10-01'],
y = [25,100,20,7,38,170,200],
name='Debit',
marker=dict(
color=color1
)
)
trace2 = go.Scatter(
x=['2017-09-25','2017-09-26','2017-09-27','2017-09-28','2017-09-29','2017-09-30','2017-10-01'],
y = [3,50,20,7,38,60,100],
name='Taux',
yaxis='y2'
)
data = [trace1, trace2]
layout = go.Layout(
title= ('Chart Number: '+str(i)),
titlefont=dict(
family='Courier New, monospace',
size=15,
color='#7f7f7f'
),
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
yaxis=dict(
title='Bandwidth Mbit/s',
titlefont=dict(
color=color1
),
tickfont=dict(
color=color1
)
),
yaxis2=dict(
title='Ratio %',
overlaying='y',
side='right',
titlefont=dict(
color=color2
),
tickfont=dict(
color=color2
)
)
)
fig = go.Figure(data=data, layout=layout)
plotly.offline.plot(fig, filename='Chart_'+str(i)+'.html',auto_open=False)
fichier_html_graphs.write(" <object data=\""+'Chart_'+str(i)+'.html'+"\" width=\"650\" height=\"500\"></object>"+"\n")
else:
break
fichier_html_graphs.write("</body></html>")
print("CHECK YOUR DASHBOARD.html In the current directory")
Result:
I used two side by side Div elements to emulate Plotly subplot. Doing this way, we have independent legends. However, if we want to share an axis, we should do it manually:
app.layout = html.Div(children=[
html.Div(['YOUR FIRST GRAPH OBJECT'],
style = {'float':'left', 'width':'49%'}) ,
html.Div(['YOUR SECOND GRAPH OBJECT'],
style = {'float':'right', 'width':'49%'})
])

Categories