I have the following code for a vertical rectangle in plotly express:
fig.add_vrect(
x0 = '2020-04',
x1 = '2020-09',
fillcolor="red",
opacity=0.25
)
I would like to make a button where the user can toggle with rectangle on and off, and when it's on there's some text in the middle. I would like them to be off by default.
You can use dictionaries to create your rectangle shape and rectangle annotation and then use these as arguments for a button. A few details: we use the "relayout" method for buttons because toggling a shape and text annotation means we are only changing the layout, and args and args2 tells the button how to behave when toggled on/off.
Edit: in order to keep another shape (like a vline) on the figure, you can add the vline to both args and args2 of your button so the vline remains when the button is toggled
import plotly.express as px
fig = px.scatter(
x=['2020-01-30', '2020-04-01', '2020-04-01','2020-09-01'],
y=[3,2,3,2]
)
fig.add_vline(
x='2020-02',
line_dash='dash'
)
vline_shape = [dict(
type='line',
x0='2020-02',
x1='2020-02',
xref='x',
y0=0,
y1=1,
yref='y domain',
line= {'dash': 'dash'}
)]
rectangle_shape = [dict(
type='rect',
x0='2020-04',
x1='2020-09',
xref='x',
y0=0,
y1=1,
yref='y domain',
fillcolor='red',
opacity=0.25
)]
rectangle_annotation = [dict(
showarrow=False,
x='2020-06-15',
y=2.5,
text="Selected Time Period"
)]
fig.update_layout(
updatemenus=[
dict(
type="buttons",
buttons=[
dict(label="Toggle Rectangle",
method="relayout",
args=[{
"shapes": rectangle_shape + vline_shape,
"annotations": rectangle_annotation}],
args2=[{
"shapes": vline_shape,
"annotations": []}]),
# dict(label="Untoggle Rectangle",
# method="relayout",
# args=["shapes", []]),
],
)
]
)
fig.show()
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)
I am trying to put images on my figure, like a watermark, I am following the documentation. and it works with the 'Vox' example. However, when I try to put local images to the figure they do not show up.
Here is my code:
import plotly.express as px
import requests
import pandas as pd
response = requests.get("https://api.covalenthq.com/v1/1/address/0x343A53A1E8b17beDd15F47a28195Bc8C120d4443/portfolio_v2/?format=format%3Dcsv&key=ckey_57eeb470248541708eeaf028c9d").json()['items']
data=pd.json_normalize(response,record_path=['holdings'],meta=['contract_ticker_symbol','contract_name',"contract_address"])
data['timestamp']=pd.to_datetime(data['timestamp']).dt.strftime('%D')
#colors = {
# 'background': 'black', #Sets plot background color black
# 'text': '#FFFFFF' #Sets plot text color white
#}
fig = px.line(data, x="timestamp", y="close.quote", color="contract_name",color_discrete_sequence=["#ff4c8b", "#00d8d5",'#f7f7f7'], line_group="contract_ticker_symbol",labels={ #Changes colum names
"contract_name":'Contract Name',
"timestamp": "Date",
"close.quote": "USD Value",
"contract_ticker_symbol": "Ticker"
}, title='Asset Value Over Time', hover_name="contract_ticker_symbol")
fig.add_layout_image(
dict(
source="vox.png",
xref="paper", yref="paper",
x=0.5, y=0.24,
sizex=0.5, sizey=0.6,
xanchor="center", yanchor="bottom"
)
)
fig.add_layout_image(
dict(
source="aa_footer.svg",
xref="paper", yref="paper",
x=0.7, y=(-0.20),
sizex=1.7, sizey=.8,
xanchor="center", yanchor="bottom"
)
)
fig.update_layout(plot_bgcolor='black', paper_bgcolor='black',font_color='#FFFFFF')
# update layout properties
fig.update_layout(
margin=dict(r=20, l=300, b=75, t=125),
title=("Asset Valuation Overtime<br>" +
"<i>Assets in Ethereum Blockchain</i>"),
)
fig.update_xaxes(showgrid=False) #hide vertical gridlines
fig.show()
I tried with both putting my images into 'assets' folder and outside as well as uploading them to imgBB. still no response
This is the figure I am getting:
[![enter image description here][2]][2]
Can somebody please tell me how to fix this problem
The easiest way to do this is to specify the data obtained by using the PILLOW library as the source. The official reference description can be found here.
from PIL import Image # new import
img = Image.open('./data/vox.png') # image path
# defined to source
fig.add_layout_image(
dict(
source=img,
xref="paper", yref="paper",
x=0.5, y=0.24,
sizex=0.5, sizey=0.6,
xanchor="center",
yanchor="bottom",
opacity=0.5
)
)
x2016 = data[data.year == 2016].iloc[:20,:]
num_students_size = [float(each.replace(',', '.')) for each in x2016.num_students]
international_color = [float(each) for each in x2016.international]
trace1 = go.Scatter(
x = x2016.world_rank,
y = x2016.teaching,
mode = "markers",
marker=dict(
color = international_color,
size = num_students_size,
showscale = True
),
text = x2016.university_name
)
data5 = [trace1]
iplot(data5)
This gives bubble plot and it does not show labels . How to add labels please help]1
Your [data5] would be better suited as a go.Figure() object.
There is a good sequence here to follow: https://plotly.com/python/line-and-scatter/#bubble-scatter-plots
Here is the reference to figure labels:
https://plotly.com/python/figure-labels/
fig.update_layout(
title="Plot Title",
xaxis_title="x Axis Title",
yaxis_title="y Axis Title",
font=dict(
family="Courier New, monospace",
size=18,
color="#7f7f7f"
)
)
fig.show()
Additional relevant help and tutorials here:
https://plotly.com/python/line-and-scatter/
So - to give a generic hint here, something like the following should work:
data5 = go.Figure(data=trace1,
title="Plot Title",
xaxis_title="x Axis Title",
yaxis_title="y Axis Title"
)
iplot(data5)
I'm trying to make an animated scatter plot over fixed surface using plotly.
This is a code I use to draw the surface:
import plotly.graph_objects as go
def surface(x, y, z, opacity: float = 1.0) -> go.Figure:
fig = go.Figure()
fig.add_trace(
go.Surface(
x=x,
y=y,
z=z,
contours_z=dict(
show=True,
usecolormap=True,
project_z=True,
),
opacity=opacity
)
)
return fig
Then I'm trying to overlay scatter plots over it.
def population(
self,
benchmark: CEC2013,
batch_stats: BatchStats,
filename: str = 'population'
):
# Here I'm creating the surface figure using previous method
surface = figure.surface.surface(*benchmark.surface, opacity=0.8)
frames = []
# Time to add some frames using Scatter 3D
for population in batch_stats.population_history:
x = [solution.genome[0] for solution in population.solutions]
y = [solution.genome[1] for solution in population.solutions]
fitness = population.fitness
frame = go.Frame(
data=[
go.Scatter3d(
x=x,
y=y,
z=fitness,
mode='markers',
marker=dict(
size=6,
color='#52CA34',
)
)
]
)
frames.append(frame)
# Update frames to root figure
surface.frames = frames
# just a fancy display, to make it work in offline mode in html render from notebook
pyo.iplot(
surface,
filename=filename,
image_width=self.IMAGE_WIDTH,
image_height=self.IMAGE_HEIGHT
)
Surface displays only in a first frame. Scatter plots are displayed in subsequent frames, but without underlaying surface.
Code is located here on a dev branch. There's debug notebook named test_vis.ipynb at the root. Thanks for help <3
I've posted this question as an issue at plotly's repository.
Here's an answer I've received.
#empet - thank you <3
When your fig.data contains only one trace then it is supposed that each frame updates that trace
and the trace is no more displayed during the animation.
That's why you must define:
fig = go.Figure(
data=[
go.Scatter(
y=y,
x=x,
mode="lines",
ine_shape='spline'
)
]*2
)
i.e. include the same trace twice in fig.data.
At the same time modify the frame definition as follows:
frame = go.Frame(data=[scatter], traces=[1])
traces = [1] informs plotly.js that each frame updates the trace fig.data[1], while fig.data[0] is unchanged during the animation.
Here's a complete example of how to make an animation over some based plot.
import math
import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
import plotly.offline as pyo
class Plot:
def __init__(
self,
image_width: int = 1200,
image_height: int = 900
) -> None:
self.IMAGE_WIDTH = image_width
self.IMAGE_HEIGHT = image_height
pyo.init_notebook_mode(connected=False)
pio.renderers.default = 'notebook'
def population(self, filename: str = 'population'):
x_spline = np.linspace(
start=0,
stop=20,
num=100,
endpoint=True
)
y_spline = np.array([math.sin(x_i) for x_i in x_spline])
x_min = np.min(x_spline)
x_max = np.max(x_spline)
y_min = np.min(y_spline)
y_max = np.max(y_spline)
spline = go.Scatter(
y=y_spline,
x=x_spline,
mode="lines",
line_shape='spline'
)
fig = go.Figure(
data=[spline] * 2
)
frames = []
for i in range(50):
x = np.random.random_sample(size=5)
x *= x_max
y = np.array([math.sin(x_i) for x_i in x])
scatter = go.Scatter(
x=x,
y=y,
mode='markers',
marker=dict(
color='Green',
size=12,
line=dict(
color='Red',
width=2
)
),
)
frame = go.Frame(data=[scatter], traces=[1])
frames.append(frame)
fig.frames = frames
fig.layout = go.Layout(
xaxis=dict(
range=[x_min, x_max],
autorange=False
),
yaxis=dict(
range=[y_min, y_max],
autorange=False
),
title="Start Title",
updatemenus=[
dict(
type="buttons",
buttons=[
dict(
label="Play",
method="animate",
args=[None]
)
]
)
]
)
fig.update_layout(
xaxis_title='x',
yaxis_title='y',
title='Fitness landscape',
# autosize=True
)
pyo.iplot(
fig,
filename=filename,
image_width=self.IMAGE_WIDTH,
image_height=self.IMAGE_HEIGHT
)
plot = Plot()
plot.population()
I am building a dashboard using Potly Dashboard. I am using a dark bootstrap theme therefore I don't want a white background.
However, my map now looks like this:
And the code that produced it is shown below:
trace_map = html.Div(
[
dcc.Graph(
id = "map",
figure = go.Figure(
data=go.Choropleth(
locations=code, # Spatial coordinates
z = df.groupby(['month']).sum()['Sales'].astype(int),
locationmode = 'USA-states',
colorscale = 'Reds',
colorbar_title = "USD",
), layout = go.Layout(title = 'The Cities Sold the Most Product',
font = {"size": 9, "color":"White"},
titlefont = {"size": 15, "color":"White"},
geo_scope='usa',
margin={"r":0,"t":40,"l":0,"b":0},
paper_bgcolor='#4E5D6C',
plot_bgcolor='#4E5D6C',
)
)
)
]
)
I have tried paper_bgcolor, and plot_bgcolor but couldn't make it work.
Ideally I would like to achieve how this image looks (please ignore the red dots):
Generally:
fig.update_layout(geo=dict(bgcolor= 'rgba(0,0,0,0)'))
And in your specific example:
go.Layout(geo=dict(bgcolor= 'rgba(0,0,0,0)')
Plot:
Code:
import plotly.graph_objects as go
fig = go.Figure(
data=go.Choropleth(
#locations=code, # Spatial coordinates
#z = df.groupby(['month']).sum()['Sales'].astype(int),
locationmode = 'USA-states',
colorscale = 'Reds',
colorbar_title = "USD",
), layout = go.Layout(geo=dict(bgcolor= 'rgba(0,0,0,0)'),
title = 'The Cities Sold the Most Product',
font = {"size": 9, "color":"White"},
titlefont = {"size": 15, "color":"White"},
geo_scope='usa',
margin={"r":0,"t":40,"l":0,"b":0},
paper_bgcolor='#4E5D6C',
plot_bgcolor='#4E5D6C',
)
)
fig.show()
And you might want to change the color of the lakes too. But do note that setting lakecolor = 'rgba(0,0,0,0)' will give the lakes the same color as the states and not the bakground. So I'd go with lakecolor='#4E5D6C'. You could of course do the same thing with bgcolor, but setting it to 'rgba(0,0,0,0)' gets rid of the white color which you specifically asked for.
Lake color plot:
Lake color code:
import plotly.graph_objects as go
fig = go.Figure(
data=go.Choropleth(
#locations=code, # Spatial coordinates
#z = df.groupby(['month']).sum()['Sales'].astype(int),
locationmode = 'USA-states',
colorscale = 'Reds',
colorbar_title = "USD",
), layout = go.Layout(geo=dict(bgcolor= 'rgba(0,0,0,0)', lakecolor='#4E5D6C'),
title = 'The Cities Sold the Most Product',
font = {"size": 9, "color":"White"},
titlefont = {"size": 15, "color":"White"},
geo_scope='usa',
margin={"r":0,"t":40,"l":0,"b":0},
paper_bgcolor='#4E5D6C',
plot_bgcolor='#4E5D6C',
)
)
fig.show()
And we could just as well change the state border colors, or what is more cryptically known as subunitcolor in this context. And to better match your desired endresult we could spice up the landcolor as well:
State border and state colors, plot:
State border and state colors, code:
import plotly.graph_objects as go
fig = go.Figure(
data=go.Choropleth(
#locations=code, # Spatial coordinates
#z = df.groupby(['month']).sum()['Sales'].astype(int),
locationmode = 'USA-states',
colorscale = 'Reds',
colorbar_title = "USD",
), layout = go.Layout(geo=dict(bgcolor= 'rgba(0,0,0,0)', lakecolor='#4E5D6C',
landcolor='rgba(51,17,0,0.2)',
subunitcolor='grey'),
title = 'The Cities Sold the Most Product',
font = {"size": 9, "color":"White"},
titlefont = {"size": 15, "color":"White"},
geo_scope='usa',
margin={"r":0,"t":40,"l":0,"b":0},
paper_bgcolor='#4E5D6C',
plot_bgcolor='#4E5D6C',
)
)
fig.show()
I found my way here because I wanted to change the theme of my Choroplethmapbox. The accepted solution helped, but ultimately I found the code below worked for my situation:
instantiate figure
fig = go.Figure()
add some traces
fig.add_trace(go.Choroplethmapbox(geojson=data_for_choropleth_geojson,
locations=data_for_choropleth['fips'],
z=data_for_choropleth['total_population'],
featureidkey='properties.fips'
))
finally, change the theme using update_layout
fig.update_layout(
hovermode='closest',
mapbox=dict(
# style options: "basic", "streets", "outdoors",
# "dark", "satellite", or "satellite-streets","light"
# "open-street-map", "carto-positron",
# "carto-darkmatter", "stamen-terrain",
# "stamen-toner" or "stamen-watercolor"
style='light',
bearing=0,
pitch=0,
accesstoken=TOKEN,
zoom=5,
center=dict(
lat=29.4652568,
lon=-98.613121
)
)