简体   繁体   English

如何使用 Plotly Choropleth 显示分类变量的所有值

[英]How to display all the values of the categorical variable using Plotly Choropleth

The task is to display the state wise category when mouse is hovered over the state, but it is displaying only the last option for all the states which is vegetables.任务是当鼠标悬停在 state 上时显示 state 明智类别,但它只显示所有状态的最后一个选项,即蔬菜。

Here is the code which I have tried.这是我试过的代码。

fig = px.choropleth(data, 
                    locations="id", 
                    geojson=state,
                    color="Category",
                    hover_name="State",
                    scope="usa",
                    hover_data = ["Year", "Dollars"]
                    )

fig.show()

The result which I am getting now.我现在得到的结果。

在此处输入图像描述

How can I display all the values which are there in Category variable?如何显示类别变量中的所有值?

Dataset Link: https://github.com/satyam2829/Choropleth数据集链接: https://github.com/satyam2829/Choropleth

  • your data does not seem very suitable for what you are trying to achieve.您的数据似乎不太适合您要实现的目标。 Have de-duped and summarised进行了去重和总结
    • created ColumnList all categories in state创建ColumnList state中的所有类别
    • created Categories count of categories in state在 state 中创建的类别计数
  • modified plotly express choropleth() to use this summarised data修改plotly express choropleth()以使用此汇总数据
  • to make colors would correctly, it's normally the case you need to defined featureidkey to link dataframe column to appropriate property in GeoJSON要使 colors 正确,通常情况下您需要定义featureidkey以将 dataframe 列链接到 GeoJSON 中的适当属性
import requests
import pandas as pd
import numpy as np
import plotly.express as px

state = requests.get(
    "https://raw.githubusercontent.com/satyam2829/Choropleth/main/us-states.json"
).json()
data = pd.read_csv(
    "https://raw.githubusercontent.com/satyam2829/Choropleth/main/WeeklyFoodPrices.csv"
)
data["Date"] = pd.to_datetime(data["Date"])


# 1. de-dup data,  take just last date for each state
# 2. summarise data for state as each state has many categories
data = (
    data.merge(
        data.groupby("State", as_index=False).agg({"Date": "max"}),
        on=["State", "Date"],
        how="inner",
    )
    .groupby(["State", "Date"], as_index=False)
    .agg(
        Category=("Category", "last"),
        Dollars=("Dollars", "last"),
        LastYear=("LastYear", "last"),
        CategoryList=("Category", list),
        Categories=("Category","size")
    )
)

fig = px.choropleth(
    data,
    locations="State",
    featureidkey="properties.name",  # needed as this is the common property
    geojson=state,
    color="Category",
    hover_name="State",
    scope="usa",
    hover_data=["LastYear", "Dollars", "Categories", "CategoryList"],
)

fig

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM