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
)
)
Related
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()
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.
Im using the Plotly library for an interactive map in python. However, when you use this library it opens it up in chrome when I want to place the figure onto a leaflet to be used in TKinter
from tkinter import *
import csv
import sys
import plotly.graph_objects as go
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
mapbox_access_token = "pk.eyJ1IjoiY21jY3Vza2VyMTMyMiIsImEiOiJja254YjA5emEwb21rMnB0Z3Nib285OGNkIn0.PL7Nx-Q1XgSO5PBSdI2w2Q"
fig = go.Figure(go.Scattermapbox(
lat=['54.1533'],
lon=['-6.0663'],
mode='markers',
marker=go.scattermapbox.Marker(
size=14
),
text=['Mournes'],
))
fig.update_layout(
hovermode='closest',
mapbox=dict(
accesstoken=mapbox_access_token,
bearing=0,
center=go.layout.mapbox.Center(
lat=54,
lon=-6
),
pitch=0,
zoom=9
)
)
fig.show()
f = fig
I am currently doing a dataviz project, and I wish to add small images above each bar of my bar chart. For some reason, when I upload my own .png files, they can not be displayed.
When I use the .png files from the plot.ly documentation, it works fine. I produce it with the following:
new = go.Figure(data=[
go.Bar(name = 'DC Men',
x = dc_most_men.name,
y = dc_most_men.appearances,
marker_color ='rgb(244,188,60)'),
go.Bar(name = 'DC Females',
x = dc_most_females.name,
y = dc_most_females.appearances,
marker_color ='rgb(28,140,140)')
])
new.update_layout(
xaxis=dict(
showline=True,
showgrid=False,
showticklabels=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
ticks='outside',
tickfont=dict(
family='Arial',
size=12,
color='rgb(82, 82, 82)',
),
),
yaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
showticklabels=True,
),
autosize=False,
margin=dict(
autoexpand=False,
l=100,
r=20,
t=110,
),
showlegend=False,
plot_bgcolor='white'
)
new.add_layout_image(
dict(
source='https://github.itu.dk/storage/user/2360/files/eeb40480-9c3b-11ea-99e6-b9ae4b500657',
x=0.07,
y=1,
))
new.add_layout_image(
dict(
source="https://raw.githubusercontent.com/michaelbabyn/plot_data/master/benzene.png",
x=0.17,
y=0.8,
))
new.add_layout_image(
dict(
source="https://raw.githubusercontent.com/michaelbabyn/plot_data/master/benzene.png",
x=0.275,
y=0.5,
))
new.update_layout_images(dict(
xref="paper",
yref="paper",
sizex=0.1,
sizey=0.1,
xanchor="right",
yanchor="bottom"
))
Which very nicely produces the following barchart:
However, when I upload my own files to GitHub, it seems to not display the logo at all. I made sure to change the path to the following link as well.
The link I use is: https://user-images.githubusercontent.com/47081217/82669721-3b97db00-9c3c-11ea-90f6-c525e647bc49.png
Is there anything I have over-looked?
I don't think that from github could open an external link. Have you tried to download the png on the same folder where your notebook/script is?
I thought that if the format on GitHub is not the normal format, maybe the PILLOW library can handle it.
from PIL import Image
img = Image.open('https://github.itu.dk/storage/user/2360/files/eeb40480-9c3b-11ea-99e6-b9ae4b500657')
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
)
)