Добавление легенды к карте px.choropleth в Python: методы и примеры

Чтобы добавить легенду к карте px.choroplethв Python, вы можете использовать различные методы. Вот несколько вариантов:

  1. Использование plotly.graph_objects: вы можете создать объект plotly.graph_objects.Figureи добавить к нему легенду цветной полосы. Вот пример:
import plotly.graph_objects as go
import plotly.express as px
# Create the choropleth map
fig = px.choropleth(data_frame=df, ...)
# Add a color bar legend
fig.update_layout(coloraxis_colorbar=dict(title='Legend Title'))
# Display the map
fig.show()
  1. Использование атрибутов px.choropleth. Вы можете напрямую изменить атрибуты объекта px.choropleth, чтобы настроить легенду. Вот пример:
import plotly.express as px
# Create the choropleth map
fig = px.choropleth(data_frame=df, ...)
# Customize the legend
fig.update_traces(colorbar=dict(title='Legend Title'))
# Display the map
fig.show()
  1. Использование fig.add_trace: этот метод позволяет вручную добавить к фигуре трассировку цветной полосы. Вот пример:
import plotly.graph_objects as go
import plotly.express as px
# Create the choropleth map
fig = px.choropleth(data_frame=df, ...)
# Create a color bar trace
color_bar_trace = go.Scatter(
    x=[],
    y=[],
    mode='markers',
    marker=dict(
        colorscale='Viridis',
        showscale=True,
        color=[],
        cmin=0,
        cmax=1,
        colorbar=dict(title='Legend Title')
    )
)
# Add the color bar trace to the figure
fig.add_trace(color_bar_trace)
# Display the map
fig.show()

Эти методы помогут вам добавить легенду к карте px.choroplethв Python.