Как добавить аннотации к фигуре Plotly Scattermapbox/ChoroplethmapboxPython

Программы на Python
Ответить
Anonymous
 Как добавить аннотации к фигуре Plotly Scattermapbox/Choroplethmapbox

Сообщение Anonymous »

Я хочу создать карту ниже с помощью Python Plotly.
Необходимый рисунок:
Изображение

Я могу создавать слои шестиугольников, но не могу добавлять аннотации к отобразите карту и выделите определенный шестиугольник 8744a931effffff другим цветом. Вот моя реализация ниже:

Код: Выделить всё

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import h3

def create_plotly_map(final_data):
# Create the base map
fig = go.Figure()

# Add choropleth layer for hexagons
fig.add_trace(go.Choroplethmapbox(
geojson=final_data['geometry'].__geo_interface__,
locations=final_data.index,
z=final_data['Forecast'],
colorscale=['green', 'red'],
zmin=final_data['Forecast'].min(),
zmax=max(1, final_data['Forecast'].max()),
marker_opacity=0.3,
marker_line_width=0.5,
colorbar=dict(title='Rescue Demand'),
hoverinfo='none'
))

# Function to add rectangle and text annotation
def add_annotation(fig, x, y, text, color):
fig.add_annotation(
x=x,
y=y,
text=text,
showarrow=False,
font=dict(
color=color,
size=12
),
bordercolor=color,
borderwidth=200,
borderpad=4,
ax=0,  # Position relative to the x-axis
ay=0,  # Position relative to the y-axis, adjust ay for vertical placement if needed
bgcolor="rgba(255,255,255,0.7)"   # Semi-transparent background for better readability
)

# Add annotations for surge multipliers
for idx, row in final_data.iterrows():
color = row['color'][:7] if row['color'].startswith('#') and len(row['color']) == 9 else row['color']
text = f"{row['surge_mul']:.2f}x"
add_annotation(fig, row['lng'], row['lat'], text, color)

hover_data = final_data[[
'surge_mul', 'opportunity'
]]
hover_text = hover_data.apply(
lambda row: "
".join([

f"Multiplier: {row['surge_mul']}",
f"Opportunity: ${row['opportunity']}"
]),
axis=1
)

fig.add_trace(go.Scattermapbox(
lat=final_data['lat'],
lon=final_data['lng'],
mode='markers',
marker=go.scattermapbox.Marker(size=0),  # Invisible markers for hover
text=hover_text,
hoverinfo='text',
showlegend=False
))

# Update layout
fig.update_layout(
mapbox_style="open-street-map",
mapbox=dict(
center=dict(
lat=final_data['lat'].mean(),
lon=final_data['lng'].mean()
),
zoom=11
),
font=dict(
family="Rockwell",
size=14),
hoverlabel=dict(
bgcolor="white",
font_size=16,
font_family="Rockwell"
),
margin={"r":0,"t":0,"l":0,"b":0},
height=600
)

return fig

# Assuming you have your final_data DataFrame ready
fig = create_plotly_map(final_data)
fig.show()
Пример данных

Код: Выделить всё

data = pd.DataFrame({'h3_07': {0: '8744a9302ffffff',
1: '8744a9311ffffff',
2: '8744a930effffff',
3: '8744a930cffffff',
4: '8744a9315ffffff',
5: '8744a9318ffffff',
6: '8744a931dffffff',
7: '8744a9306ffffff',
8: '8744a9319ffffff',
9: '8744a931effffff',
10: '8744a931cffffff',
11: '8744a9301ffffff',
12: '8744a930affffff',
13: '8744a9303ffffff',
14: '8744a9300ffffff'},
'Forecast': {0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 0,
8: 1,
9: 0,
10: 0,
11: 1,
12: 1,
13: 1,
14: 1},
'surge_mul': {0: 1.12,
1: 1.14,
2: 2.03,
3: 1.42,
4: 1.74,
5: 1.95,
6: 1.34,
7: 1.17,
8: 1.0,
9: 1.13,
10: 1.0,
11: 1.29,
12: 1.0,
13: 1.0,
14: 1.14},
'opportunity': {0: 0.0,
1: 0.0,
2: 0.0,
3: 0.0,
4: 0.0,
5: 0.0,
6: 0.0,
7: 0.0,
8: '-',
9: 0.0,
10: '-',
11: 22.58,
12: '-',
13: '-',
14: 19.95},
'color': {0: '#008000ff',
1: '#008000ff',
2: '#008000ff',
3: '#008000ff',
4: '#008000ff',
5: '#008000ff',
6: '#008000ff',
7: '#008000ff',
8: '#ff0000ff',
9: '#008000ff',
10: '#008000ff',
11: '#ff0000ff',
12: '#ff0000ff',
13: '#008080',
14: '#ff0000ff'},
'lat': {0: 28.68958635891766,
1: 28.694991157953137,
2: 28.72110573469225,
3: 28.715694160659446,
4: 28.67382864602292,
5: 28.73191306462333,
6: 28.72651203548175,
7: 28.66841933038336,
8: 28.747676222100004,
9: 28.71615121919693,
10: 28.710750939011273,
11: 28.699934572325734,
12: 28.742274441025884,
13: 28.705345390585954,
14: 28.68417629345379},
'lng': {0: -81.54438913509742,
1: -81.52227241812639,
2: -81.57673277797278,
3: -81.59886857103568,
4: -81.52822959753617,
5: -81.53247482786799,
6: -81.55460152851583,
7: -81.55034359990239,
8: -81.54864440281916,
9: -81.51631344624931,
10: -81.53843287797946,
11: -81.58268538919677,
12: -81.57077837338699,
13: -81.56055686069354,
14: -81.5665104000335}})

import h3pandas
from h3 import h3
import geopandas as gpd
from shapely.geometry import Polygon, Point

def add_geometry(x):
# Get geometry points
points = h3.h3_to_geo_boundary(x, True)
# Return a hexagon polygon
return Polygon(points)

def add_geometry_to_hex(hex_df, HEX_RES_COL):
# add geometry to the dataframe
hex_df['geometry'] = hex_df[HEX_RES_COL].apply(lambda x :  add_geometry(x))
# Convert to geopandas dataframe
hex_df = gpd.GeoDataFrame(hex_df)
# return geopandas dataframe
return hex_df
final_data = add_geometry_to_hex(data, "h3_07")
Изображение

Как добавить текстовые аннотации к фигуре Scattermapbox/Choroplethmapbox??


Подробнее здесь: https://stackoverflow.com/questions/790 ... box-figure
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»