如何在 Plotly Choropleth 地图中修改国家边界粗细、颜色和样式?

问题描述 投票:0回答:2

有人可以告诉我为什么我的

go.Choropleth
代码的这一部分不起作用吗?

我正在尝试让我的国家的边界更粗、更黑,但它不起作用,我不知道这些布局规范中还可能缺少什么。这是我的地图代码部分,在其下面您可以看到生成的地图的放大部分。请注意,该国的边界仍然又细又灰——为什么它没有改变?

map_fig_layout = {'coloraxis_colorbar': {'title': 'População (%)',
                                                  'thickness': 20,                  
                                                'ticklabelposition':'outside bottom'},
                         'margin': {'r':0, 'l':0, 't':0, 'b':0},
                         'template': 'plotly_dark',
                         'geo':{'projection': go.layout.geo.Projection(type ='natural earth'),
                                'landcolor': '#262626',
                                'showcountries':True,
                                'showsubunits':True,
                                'subunitcolor': 'black',
                                'subunitwidth': 4,
                                'resolution':110,
                                'visible':True,
                                'countrywidth': 4,
                                'countrycolor' : 'black'},                       
                         'uirevision':'not_tracked_key'}

       map_graph = go.Figure({'data':[ go.Choropleth(locations = dff['Code'],
                                                     z = dff['população_%'], # a column of dff
                                                     hovertext = dff['Entity'],
                                                     zmin = 0,
                                                     zmax = 100,
                                                     colorscale = make_colorscale( ['#F53347','#E6C730','#2FF5A8'] ),
                                                     geo = 'geo') ],
                              'layout': map_fig_layout})
    

python plotly plotly-dash plotly-python choropleth
2个回答
1
投票

尝试将此行添加到您的代码中:

fig.update_traces(marker_line_width=2.0, selector=dict(type='choropleth'))

或者根据您的情况:

map_graph.update_traces(marker_line_width=2.0, selector=dict(type='choropleth'))

如果需要,您还可以控制不透明度:

例如,

from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
                   dtype={"fips": str})

import plotly.express as px

fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
                           color_continuous_scale="Viridis",
                           range_color=(0, 12),
                           scope="usa",
                           labels={'unemp':'unemployment rate'}
                          )
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.update_traces(marker_line_width=3.0, marker_opacity=0.6, selector=dict(type='choropleth'))
fig.show()

文档参考

https://plotly.com/python/reference/choropleth/#choropleth-marker


1
投票
  • 使用您的代码(确保将其格式化为符合 PEP8 格式以应对未来的问题)
  • kaggle 获取了一些数据,使其成为可重复生成的示例
  • 子单位的示例是一个国家/地区的县/地区
import kaggle.cli
import sys, requests
import pandas as pd
from pathlib import Path
from zipfile import ZipFile
import urllib
import plotly.graph_objects as go
from plotly.colors import make_colorscale

# fmt: off
# download data set
url = "https://www.kaggle.com/mohaiminul101/population-growth-annual"
sys.argv = [sys.argv[0]] + f"datasets download {urllib.parse.urlparse(url).path[1:]}".split(" ")
kaggle.cli.main()
zfile = ZipFile(f'{urllib.parse.urlparse(url).path.split("/")[-1]}.zip')
dfs = {f.filename: pd.read_csv(zfile.open(f)) for f in zfile.infolist()}
# fmt: on

dff = dfs["world_population_growth.csv"].rename(
    columns={"Country Code": "Code", "2019": "população_%", "Country Name": "Entity"}
)
dff["população_%"] = dff["população_%"] * 100
map_fig_layout = {
    "coloraxis_colorbar": {
        "title": "População (%)",
        "thickness": 20,
        "ticklabelposition": "outside bottom",
    },
    "margin": {"r": 0, "l": 0, "t": 0, "b": 0},
    "template": "plotly_dark",
    "geo": {
        "projection": go.layout.geo.Projection(type="natural earth"),
        "resolution": 110,
        "visible": True,
    },
    "uirevision": "not_tracked_key",
}

map_graph = go.Figure(
    {
        "data": [
            go.Choropleth(
                locations=dff["Code"],
                z=dff["população_%"],  # a column of dff
                hovertext=dff["Entity"],
                zmin=0,
                zmax=100,
                marker={"line":{"width":4, "color":"black"}},
                colorscale=make_colorscale(["#F53347", "#E6C730", "#2FF5A8"]),
            )
        ],
        "layout": map_fig_layout,
    }
)

map_graph

© www.soinside.com 2019 - 2024. All rights reserved.