添加注释到Plotly Scatter Map

时间:2016-03-23 20:33:33

标签: python pandas plotly

我无法在我的情节散点图中添加注释。我使用pandas数据帧作为我的数据源,列Lat,Long,文本是索引。嵌套在layout参数下的结果annotations参数如下所示:

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

相反,我可以使用一行使用单个注释(甚至可以使用硬编码值进行测试)。似乎x,y放置使用图表网格而不是地图网格来放置注释。是否有一个参数来解决这个问题,还是需要调整图表网格本身?提前谢谢。

编辑:这是一个例子。我想通过将Lat / Long坐标作为注释的x,y变量传递给每个气泡旁边的注释。

plotly map example

1 个答案:

答案 0 :(得分:0)

您可以尝试与that类似的内容:

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')

OLD答案:

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()

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

Plot