添加下拉按钮以绘图表达等值线图

Posted

技术标签:

【中文标题】添加下拉按钮以绘图表达等值线图【英文标题】:Add dropdown button to plotly express choropleth map 【发布时间】:2021-11-13 01:07:01 【问题描述】:

我已经看到了这个,我正在尝试构建这个解决方案 (Dropdown menu for Plotly Choropleth Map Plots),但我不断收到可见部分的错误,这是我的代码。

import pandas as pd
import numpy as np
import plotly.graph_objs as go
import plotly.express as px

# Data
cols_dd = ["Total tests", "Total cases", "Total deaths"]
# 
visible = np.array(cols_dd)

# define traces and buttons at once
traces = []
buttons = []
for value in cols_dd:
    traces.append(px.choropleth(df,
       locations="Iso code", # Spatial coordinates
        color=value, # Data to be color-coded
        hover_data='Iso code':False, 'Vaccines':True, 'Total tests':': ,0.f', 'Recent cases':': ,0.f', 'Total cases':': ,0.f','Total deaths':': ,0.f','Total vaccinations':': ,0.f','People vaccinated':': ,0.f','Population':': ,0.f','Vaccination policy':': 0.f',
        color_continuous_scale="spectral_r",
        hover_name="Location",)).update_traces(visible= True if value==cols_dd[0] else False)

buttons.append(dict(label=value, method="update", args=["visible":list(visible==value), "title":f"<b>value</b>"]))

updatemenus = ["active":0,"buttons":buttons]

layout = go.Layout(
    showlegend=True,
    font=dict(size=12),
    width = 800,
    height = 500,
    margin=dict(l=0,r=0,b=0,t=40)
    )


# Show figure
fig = go.Figure(data=traces, layout=dict(updatemenus=updatemenus))
# This is in order to get the first title displayed correctly
first_title = cols_dd[0]
fig.update_layout(layout)
fig.update_geos(scope="africa")
fig.update_layout(title=f"<b>first_title</b>",title_x=0.5)
fig.show()

我收到错误消息“NoneType”对象没有属性“update_traces”,如果有可能修复破折号,将不胜感激

【问题讨论】:

您有任何数据可以在我的环境中尝试吗?另外,可见性不应该包含在等值线中吗? 只要县 iso_code 和每列的随机数就可以了,例如这里有一些国家 ZWE、ZMB、UGA、TUN、TGO 的 iso 代码。至于可见的那是我在使用它时遇到问题的地方,而不是图形对象 【参考方案1】: OWID 数据几乎就是您所使用的。列名略有不同,因此重命名为使用 从根本上说,系统地构建跟踪和布局的方式 为每个跟踪创建了 colorbar 配置,以确保其响应速度更快 扩展了 cols_dd 以展示如何使用它来绘制更多指标 根据 cmets 包括 scatter 和 choropleth
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import itertools

# get OWID data
df = pd.read_csv(
    "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/latest/owid-covid-latest.csv"
)
# rename columns as sample code uses other names....
df = df.rename(
    columns=
        "location": "Location",
        "iso_code": "Iso code",
        "total_tests": "Total tests",
        "people_vaccinated_per_hundred": "Vaccines",
        "new_cases": "Recent cases",
        "total_cases": "Total cases",
        "total_deaths": "Total deaths",
        "total_vaccinations": "Total vaccinations",
        "people_vaccinated": "People vaccinated",
        "population": "Population",
        "total_boosters": "Vaccination policy",
    
).fillna(0)
cols_dd = ["Total tests", "Total cases", "Total deaths", "Recent cases", "new_deaths"]
hd = 
    "Iso code": False,
    "Vaccines": True,
    "Total tests": ": ,0.f",
    "Recent cases": ": ,0.f",
    "Total cases": ": ,0.f",
    "Total deaths": ": ,0.f",
    "Total vaccinations": ": ,0.f",
    "People vaccinated": ": ,0.f",
    "Population": ": ,0.f",
    "Vaccination policy": ": 0.f",


fig = go.Figure()

for i, value in enumerate(cols_dd):
    # use a different color axis for each trace... makes it more responsive
    ca = f"coloraxisi+2"

    figc = px.choropleth(
        df,
        locations="Iso code",  # Spatial coordinates
        color=value,  # Data to be color-coded
        hover_data=hd,
        color_continuous_scale="spectral_r",
        hover_name="Location",
    ).update_traces(visible=False, coloraxis=ca)
    figs = px.scatter_geo(
        df,
        locations="Iso code",  # Spatial coordinates
        color=value,  # Data to be color-coded
        hover_data=hd,
        color_continuous_scale="spectral_r",
        hover_name="Location",
    ).update_traces(visible=False, marker="coloraxis": ca)

    fig = fig.add_traces(figc.data)
    fig = fig.add_traces(figs.data)
    fig = fig.update_layout(
        
            ca: 
                "cmin": df[value].replace(0, np.nan).quantile(0.25),
                "cmax": df[value].replace(0, np.nan).quantile(0.75),
                "colorbar": "title": value,
            
        
    )


fig.update_layout(
    updatemenus=[
        
            "buttons": [
                
                    "label": f"m - p",
                    "method": "update",
                    "args": [
                        
                            "visible": [
                                (m2 == m and p2 == p)
                                for m2, p2 in itertools.product(
                                    cols_dd, ["choropleth", "scatter"]
                                )
                            ]
                        ,
                        "title": f"<b>m</b>",
                    ],
                
                for m, p in itertools.product(cols_dd, ["choropleth", "scatter"])
            ]
        
    ],
    margin="l": 0, "r": 0, "t": 25, "b": 0,
)

【讨论】:

非常感谢 rob,这效果很好,请问我是否可以再问一个问题......如果我想在散点图上重复相同的过程但使用 2 滴在哪里我可以在两边的变量(例如 Total tests 和 Total cases,或 Recent cases 和 Total cases )之间切换,你能不能给我分享一个示例解决方案。我尝试用字典替换这个 (cols_dd = ["Total tests", "Total cases", "Total death"] ) 和 this (for value in cols_dd: ) with for k,v in cols_dd.items(): and使用 k 和 v 代替值,但它返回错误。 已更新 - 使用 updatemenus 中的列表创建更多跟踪和控制可见性的情况 感谢您的时间和回复,但我的意思不是在等值线图中,我的意思是尝试构建一个完全不同的散点图。我在这里用更好的例子和解释问了这个问题***.com/questions/69242033/… 关于我的第一个问题,我非常满意和感激。 我已经回答了第二个问题,如果这些答案符合您的问题,请考虑遵循 SO 礼仪并接受答案

以上是关于添加下拉按钮以绘图表达等值线图的主要内容,如果未能解决你的问题,请参考以下文章

MATLAB绘图—三维等值线绘图(contour3)

excel 折线图怎么添加折线图名称,纵坐标名称和横坐标名称

excel绘制散点图时,如何进行分组绘图?

怎样用ArcGis中的Kriging插值法绘制等值线图

如何将柱形图和折线图合为一张图表?

C# 动态添加2级下拉菜单问题