Related
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)
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()
I have a out dataframe containing two columns, Actual_Values and Predicted_Values.
I am trying to create a graph:
import pandas as pd
import plotly.graph_objects as go
x_data = out.index
trace1 = go.Scatter(
x=x_data,
y=out['Actual_Values'],
name="Actual Values"
)
trace2 = go.Scatter(
x=x_data,
y=out['Predicted_Values'],
name="Predictions"
)
traces = [trace1, trace2]
layout = go.Layout(
xaxis=dict(
autorange=True
),
yaxis=dict(
autorange=True
)
)
fig = go.Figure(data=traces, layout=layout)
plot(fig, include_plotlyjs=True)
which gives:
however, I need a graph, in which the blue line's changes to some other color from the start of the red line.
Does this help you?
import pandas as pd
import numpy as np
import plotly.graph_objects as go
# Data
n = 150
n_pred = 10
df1 = pd.DataFrame(
{"x": np.arange(n),
"actual_value": np.random.randint(0, 100, n)})
df2 = pd.DataFrame(
{"x": np.arange(n-n_pred, n),
"predicted_value": np.random.randint(0, 100, n_pred)})
# You need Outer join when prediction range is
# larger than actual value one.
df = pd.merge(df1, df2, on="x", how="outer")
idx_min = df[df["predicted_value"].notnull()].index[0]
# Plot
trace1 = go.Scatter(
x=df["x"][:idx_min+1],
y=df['actual_value'][:idx_min+1],
name="Actual Values",
line=dict(color="blue")
)
trace2 = go.Scatter(
x=df["x"][idx_min:],
y=df['actual_value'][idx_min:],
name="Actual Values",
mode="lines",
line=dict(color="green"),
showlegend=False
)
trace3 = go.Scatter(
x=df["x"],
y=df['predicted_value'],
name="Predicted Values",
line=dict(color="red")
)
traces = [trace1, trace2, trace3]
layout = go.Layout(
xaxis=dict(
autorange=True
),
yaxis=dict(
autorange=True
)
)
fig = go.Figure(data=traces, layout=layout)
fig.show()
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()
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%'})
])