向 Plotly 散点图添加注释

fis*_*all 6 python pandas plotly

我在向我的散点图添加注释时遇到问题。我使用 pandas 数据框作为我的数据源,其中包含 Lat、Long 列,文本是索引。我生成的嵌套在布局参数下的注释参数如下所示:

[dict(x= d[1]['Lat'], y= d[1]['Long'], text= d[0]) for d in df.iterrows()]
Run Code Online (Sandbox Code Playgroud)

相反,我可以只使用一行的单个注释(甚至出于测试目的硬编码值)。看起来 x,y 放置是使用图表网格而不是地图网格来放置注释。是否有参数可以解决这个问题,或者我是否需要调整图表网格本身?先感谢您。

编辑:这是一个例子。我希望通过将纬度/经度坐标作为注释的 x,y 变量传递来将注释放在每个气泡旁边。

绘制地图示例

Max*_*axU 1

您可以尝试类似的操作

import plotly.plotly as py
import plotly.graph_objs as go

fig = go.Figure(
    data=[
        go.Scattergeo(
            lat=[45.5,43.4,49.13,51.1,53.34,45.24,44.64,48.25,49.89,50.45],
            lon=[-73.57,-79.24,-123.06,-114.1,-113.28,-75.43,-63.57,-123.21,-97.13,-104.6],
            marker={
                "color": ["#bebada","#fdb462","#fb8072","#d9d9d9","#bc80bd","#b3de69","#8dd3c7","#80b1d3","#fccde5","#ffffb3"],
                "line": {
                    "width": 1
                },
                "size": 10
            },
            mode="markers+text",
            name="",
            text=["Montreal","Toronto","Vancouver","Calgary","Edmonton","Ottawa","Halifax","Victoria","Winnepeg","Regina"],
            textfont={
                "color": ["#bebada","#fdb462","#fb8072","#d9d9d9","#bc80bd","#b3de69","#8dd3c7","#80b1d3","#fccde5","#ffffb3"],
                "family": ["Arial, sans-serif","Balto, sans-serif","Courier New, monospace","Droid Sans, sans-serif","Droid Serif, serif","Droid Sans Mono, sans-serif","Gravitas One, cursive","Old Standard TT, serif","Open Sans, sans-serif","PT Sans Narrow, sans-serif","Raleway, sans-serif","Times New Roman, Times, serif"],
                "size": [22,21,20,19,18,17,16,15,14,13]
            },
            textposition=["top center","middle left","top center","bottom center","top right","middle left","bottom right","bottom left","top right","top right"]
        )
    ],
    layout={
        "title": "Canadian cities",
        "geo": {
            "lataxis": {
                "range": [40, 70]
            },
            "lonaxis": {
                "range": [-130, -55]
            },
            "scope": "north america"
        }
    }
)

plot_url = py.plot(fig, filename='Canadian Cities')
Run Code Online (Sandbox Code Playgroud)

旧答案:

import pandas as pd

# initial position
lat = 47.8388
lon = 35.1396

# generate random coordinates
df = pd.DataFrame({'lat': lat + np.random.normal(1,0.2,10),'lon': lon + np.random.normal(1,0.2,10)})
df = df.round(4)

pd.options.display.float_format = '{:.4f}'.format
df['text'] = df.lat.astype(str) + ', ' + df.lon.astype(str)
print(df)

ax = df.plot(x='lat', y='lon', kind='scatter')

y_shift = (df.lon.max()-df.lon.min())/len(df)
[ax.annotate(tup[2], xy=tup[:2], xytext=(tup[0], tup[1]))
 for tup in df.itertuples(index=False)]

plt.show()
Run Code Online (Sandbox Code Playgroud)

我将坐标作为注释文本......

阴谋