Plotly background images

北慕城南 提交于 2019-12-02 01:13:56

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")])

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!