Reputation: 1524
I'm trying to get a background image on my graph using plotly. I can't seem to get ANY image to display without using one of the images.plot.ly links. I tried web URLs and local images in the same folder as the project. This is what is showing up when I used the image URL from their tutorial:
https://plot.ly/python/images/
This is the only time I can get anything to show up. Any other link just produces nothing on the graph. Any tips? I have searched high and low for this.
layout = dict(title = 'Crime Cluster Statistics',
yaxis = dict(zeroline = False),
xaxis = dict(zeroline = False),
images= [dict(
source= "https://images.plot.ly/language-icons/api-home/python-logo.png",
xref= "x",
yref= "y",
x= 0,
y= 3,
sizex= 150000,
sizey= 150000,
sizing= "stretch")]
)
What I actually REALLY want is to fit an image of a US state on the background of the image, as the dots are supposed to represent events at a GPS coordinate for that state. But I can't seem to get any image to load onto the background besides this one.
Upvotes: 3
Views: 8400
Reputation: 57
In case this helps someone else looking for how to get a local image working as a plotly plot background, here's what I used to get it working:
figure = {'data': data,
'layout': {'xaxis': {'range': [-800, 800], 'autorange': False, 'dtick':100, 'title':'South'},
'yaxis': {'range': [-800, 800], 'autorange': False, 'dtick':100,'title': 'West (km)'},
'title': 'Sample LEO1 Main-Lobe Ground Contour (4.5 deg)',
'autosize':False, 'width':1.5*437, 'height':1.5*615,
'images': [{'source': "C:\\map.jpg",
'sizing': 'stretch', 'xref': 'paper', 'yref': 'paper', 'x':0,'y':1, 'layer':'below',
'sizex':1,'sizey':1,'opacity':1
}]
},
}
... where 'data' is set up previously as a graph object.
Upvotes: 2
Reputation: 71
I was trying to do this as well (read a local image and make it my background in a plotly graph) and kept going around and around with it (likely because I am pretty new to the whole image thing and was also trying to understand base64 encoding). This is my simple solution in a Jupyter notebook using plotly offline:
import base64
with open("C:/My.png", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode()
#add the prefix that plotly will want when using the string as source
encoded_image = "data:image/png;base64," + encoded_string
Now your layout for the plotly graph can look like this (in this case - keep in mind that you are using the actual data ranges in the graph to place the image on it, so the x and Y have to be in the appropriate range):
"layout": Layout(title='Graph Title',
yaxis=dict(title='Y Label'),
xaxis=dict(title='X Label'),
images=[dict(
source= encoded_image,
xref= "x",
yref= "y",
x= 0,
y= 10,
sizex= 20,
sizey= 10,
sizing= "stretch",
opacity= 0.7,
layer= "below")])
Upvotes: 7