如何为plotly.express.scatter_mapbox添加标记大小图例?
解决Plotly scatter_mapbox缺失大小图例的问题
问题背景
使用plotly.express.scatter_mapbox制作沙特阿拉伯境内机构可视化地图时,标记颜色对应Cluster类别(已自动生成颜色图例),标记大小关联pub_counts(出版物数量)——数量越多标记越大,但默认仅显示颜色图例,缺少解释标记大小的图例,需要补充刻度式大小图例或说明文字。
方案一:添加刻度式大小图例
由于Plotly Express的scatter_mapbox默认不支持自动生成大小图例,可通过手动添加隐藏参考点的方式创建自定义刻度式图例:
if plot_map == True: import plotly.express as px import plotly.io as pio import numpy as np pio.renderers.default='browser' fig = px.scatter_mapbox(Institutes_SA, lat="Latitude", lon="Longitude", hover_name="institution_name", mapbox_style= "carto-positron", zoom=4.5, width = 1075, height = 900, color = 'Cluster', color_discrete_sequence=['red','green','orange','DodgerBlue'], size='pub_counts', size_max = 40, opacity=0.5 ) # 选取代表性的出版物数量值作为刻度 size_ticks = [np.min(Institutes_SA['pub_counts']), np.median(Institutes_SA['pub_counts']), np.max(Institutes_SA['pub_counts'])] # 按size_max比例计算对应标记大小 size_scale = 40 / np.max(Institutes_SA['pub_counts']) legend_sizes = [int(s * size_scale) for s in size_ticks] # 添加隐藏参考点作为大小图例项 for s, label in zip(legend_sizes, size_ticks): fig.add_scattermapbox( lat=[None], # 不显示在地图上 lon=[None], mode='markers', marker=dict(size=s, color='gray', opacity=0.8), name=f'{label} 出版物' ) # 调整图例布局,合并颜色与大小图例 fig.update_layout( legend=dict( title_text='Cluster / 出版物数量', orientation='v', yanchor='top', y=1, xanchor='left', x=1.02 ) ) pio.show(fig)
方案二:添加说明文字
若不需要刻度式图例,可直接添加一行说明文字解释标记大小的含义:
if plot_map == True: import plotly.express as px import plotly.io as pio pio.renderers.default='browser' fig = px.scatter_mapbox(Institutes_SA, lat="Latitude", lon="Longitude", hover_name="institution_name", mapbox_style= "carto-positron", zoom=4.5, width = 1075, height = 900, color = 'Cluster', color_discrete_sequence=['red','green','orange','DodgerBlue'], size='pub_counts', size_max = 40, opacity=0.5 ) # 添加说明文字到图例旁 fig.add_annotation( text="标记越大表示出版物数量越多", xref="paper", yref="paper", x=1.02, y=0.95, showarrow=False, font=dict(size=12), align="left" ) pio.show(fig)
内容的提问来源于stack exchange,提问作者Kareem
相关产品推荐
相关产品推荐

