簡體   English   中英

Plotly 表達 choropleth bins

[英]Plotly express choropleth bins

我正在使用 plotly express 創建一個等值線圖。 我想使用這些 bin 有一個離散的色階:[−50,0), [0,50), [50,100), [100,150), [150,200), [200,250), [250,300), [300,350), [ 350,400)、[400,450) 和 [450,500)。 下面是我的數據框的片段。

    Country       1990   2019   Code    PGR
0   Afghanistan    12.4  38.0   AFG     206.451613
1   Albania        3.3   2.9    ALB    -12.121212
2   Algeria        25.8  43.1   DZA     67.054264

我可以顯示繪圖,但我不知道如何設置顏色。 到目前為止我的代碼是:

 fig = px.choropleth(popCodes,locations= popCodes["Code"],
                     color = popCodes["PGR"],
                     range_color = (-50, 500), 
                     hover_name = popCodes["Country"],
                     color_discrete_sequence=px.colors.sequential.Plasma)

 fig.show()

在此處輸入圖片說明

  • 似乎在 kaggle 上有一個非常相似的數據集。 有來源。 不包括PGR,因此將其計算為年度列的總和
  • 鑒於您想要離散垃圾箱,最簡單的方法是使用https://pandas.pydata.org/docs/reference/api/pandas.cut.html
  • plotly不支持pandas間隔,因此轉換為字符串.astype(str)
  • 鑒於您使用的是plotly express ,按名稱引用列比總是傳遞一個系列更簡單
  • 完整代碼如下
import kaggle.cli
import sys, requests
import pandas as pd
from pathlib import Path
from zipfile import ZipFile
import urllib
import plotly.express as px

# 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

popCodes = dfs["world_population_growth.csv"]
popCodes["PGR"] = popCodes.select_dtypes("number").sum(axis=1)
popCodes = popCodes.sort_values("PGR")

px.choropleth(
    popCodes,
    locations="Country Code",
    color=pd.cut(popCodes["PGR"], bins=range(-50, 501, 50)).astype(str),
    hover_name="Country Name",
    hover_data={"PGR":":.1f", "Country Code":True},
    color_discrete_sequence=px.colors.sequential.Plasma,
)

在此處輸入圖片說明

不像羅伯雷蒙德的回答那么整潔,但這就是我所做的。 如果我是你,我會用羅布的

popCodes['PGR'] = popCodes['PGR'].astype(float)

# Use this to bin the data and apply discrete colour codes later
conditions = [
    (popCodes['PGR'] >= -50) & (popCodes['PGR'] <0),
    (popCodes['PGR'] >= 0) & (popCodes['PGR'] <50),
    (popCodes['PGR'] >= 50) & (popCodes['PGR'] <100),
    (popCodes['PGR'] >= 100) & (popCodes['PGR'] <150),
    (popCodes['PGR'] >= 150) & (popCodes['PGR'] <200),
    (popCodes['PGR'] >= 200) & (popCodes['PGR'] <250),
    (popCodes['PGR'] >= 250) & (popCodes['PGR'] <300),
    (popCodes['PGR'] >= 300) & (popCodes['PGR'] <350),
    (popCodes['PGR'] >= 350) & (popCodes['PGR'] <400),
    (popCodes['PGR'] >= 400) & (popCodes['PGR'] <450),
    (popCodes['PGR'] >= 450) & (popCodes['PGR'] <500)
    ]
values = ['[−50,0)', '[0,50)', '[50,100)', '[100,150)', '[150,200)', 
'[150,200)', '[250,300)', '[300,350)', '[350,400)', '[400,450)', '[450,500)']
popCodes['range'] = np.select(conditions, values)




popCodes['PGR'] = popCodes['PGR'].astype(str)     # converting PGR to string gets plotly express to use discrete colours apparently
popCodes = popCodes.sort_values('range')          # sorts the dataframe by the range so I get a better legend later

fig = px.choropleth(popCodes, locations= popCodes["Code"],
                    color = popCodes["range"],                       # PGR calculated from dataframer
                    hover_name = popCodes["PGR"],                    # column to add to hover information
                    color_discrete_map={"[−50,0)": "maroon",         # discrete colours based on the range of PGR from above
                                        '[0,50)':'red',
                                        '[50,100)':'orange',
                                        '[100,150)':'yellow',
                                        '[150,200)':'lime',
                                        '[200,250)':'green',
                                        '[250,300)':'aqua',
                                        '[300,350)':'teal',
                                        '[350,400)':'blue',
                                        '[400,450)':'navy',
                                        '[450,500)':'purple'
                                       }
                   )

fig.show()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM