【问题标题】:Plotly Dash: go.Choropleth subunitwidth not workingPlotly Dash:go.Choropleth subunitwidth 不起作用
【发布时间】:2021-12-11 03:37:23
【问题描述】:

有人能告诉我为什么这部分 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 styling choropleth


    【解决方案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

    【讨论】:

    • 这确实有效,非常感谢!但我仍然想知道为什么 showsubunits、subunitwidth 和 subunitcolor 不起作用。现在我不知道是否应该将您的答案标记为实际解决方案。
    • 我相信这是因为您设置了 geo='geo',文档说这是默认设置 (plotly.com/python/reference/choropleth/#choropleth-geo)。这有点令人困惑,但 geo 与您正在编码的属性(包括子单元,正如另一个回答者指出的那样,显然是指 counties 等)不适用于 fig.Layout.geo 但 @987654332 @(见:plotly.com/python/reference/layout/#layout-template)这就是“痕迹”发挥作用的地方
    【解决方案2】:
    • 使用您的代码(确保您将其格式化为符合 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
    

    【讨论】:

    • 谢谢 Rob,下次我会以某种方式使其可重现。谢谢你的建议。我现在明白这些行是由 go.Choropleth 实例的 'markers,line' 属性控制的。
    • Tfound the solution with your answer and the anser from the John above, if I could mark 2 asnwers as the solution to my question 我会
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    相关资源
    最近更新 更多