如何将 plotly plot 嵌入到地图中

How to inlay plotly plot into a map

我在 Plotly 中创建了一个极坐标图。如果您愿意,我可以 post 创建它的代码,但这是它的图像。

我需要做的(并且不确定完成它的最佳方法)是将它插入给定的纬度,经度并能够指定它的半径(或者至少控制大小使得当地图为 panned/zoomed 时,它保持一致)。我调查了 Plotly 的地图,但我什至没有看到任何可以尝试的东西。下面是我正在尝试完成的示例(虽然我需要更小的直径,但这是在 GIMP 中制作的)

如有任何建议,我们将不胜感激。

查看了将 plotly 图添加到 folium 地图

的两个选项
  1. as popup 保留为 HTML。这效果不佳,因为弹出窗口会进入无限循环,也无法控制弹出窗口的背景颜色(因此它覆盖了地图)
  2. 作为 图像。提出了这个解决方案。这实际上是这样的:https://github.com/python-visualization/folium/blob/main/examples/ImageOverlay.ipynb
import folium
import requests
import plotly.express as px
import plotly.io
import io
from PIL import Image
import numpy as np

# create a figure
df = px.data.tips()
fig = px.pie(df, values="tip", names="day")
fig.update_layout(
    # showlegend=False,
    margin={"l": 0, "r": 0, "t": 0, "b": 0},
    paper_bgcolor="rgba(0,0,0,0)",
    plot_bgcolor="rgba(0,0,0,0)",
)

# create a folium map with US state borders...
bounds = [-124.706553, 25.120779, -66.979601, 49.383625]
m = folium.Map()
m.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
us = requests.get(
    "https://raw.githubusercontent.com/python-visualization/folium/main/examples/data/us-states.json"
).json()
folium.GeoJson(us, name="geojson").add_to(m)


# add the plotly figure as an image to folium map
def plotly_fig2array(fig, lon=-100, lat=37, size=3):
    # convert Plotly fig to  an array
    fig_bytes = fig.to_image(format="png")
    buf = io.BytesIO(fig_bytes)
    img = Image.open(buf)
    return {"image":np.asarray(img), "bounds":[[lat-size, lon-size], [lat+size, lon+size]]}


folium.raster_layers.ImageOverlay(
    **plotly_fig2array(fig, lon=-110)
).add_to(m)

m

所以这是 multi-faceted 完成的,但如果有人遇到类似的问题,我已经找到了解决方法。使用的工具是用于地图的 Leaflet 和用于绘图的 Plotly。

HTML 情节

<plotly-plot #myPlot style="width: 100%; height: 100%; display: none;" 
   [data]="myGraph.data" [config]="myGraph.config"
   [layout]="myGraph.layout" [style]="myGraph.style">
</plotly-plot>

首先,您必须确保地块的布局配置正确。

layout : {
      autosize: true,
      polar: {
        radialaxis: {
          visible: false,
          range: [0, 1]          
        },
        bgcolor:'rgba(0,0,0,0)'
      },
      showlegend: false,
      paper_bgcolor: 'rgba(0,0,0,0)'  
    }

确保背景和情节遮盖地图。

接下来,我们必须将绘图导出到图像。

@ViewChild('myPlot') public myPlot: Plotly;
Plotly.toImage(this.myPlot, {
      format: 'png',
      height: 800,
      width: 800
    }).then((url) => {
      this.addPlotToMap(url);
    })

最后,通过图像层将其添加到地图中。这将是一个半径为两英里的圆。

addPlotToMap(url){
    let TWO_MILE_RADIUS_IN_METERS = 3218.69;
    let imageBounds = L.latLng(44.671613, -89.733720).toBounds(TWO_MILE_RADIUS_IN_METERS)
    let overlay = L.imageOverlay(url,imageBounds);
    overlay.addTo(this.map);
  }