簡體   English   中英

如何使用plotly(python)中的按鈕更新直方圖nbins?

[英]How to update histogram nbins with buttons in plotly (python)?

使用按鈕更新繪圖時,我無法更新 bin 的數量。 這是一個示例性的短數據幀。 在完整版本中,有更多的行,因此使用初始 nbins = 100 是有意義的。但是,我想在更新直方圖時更改每列的 bin 數量。

dataset = pd.DataFrame(
    {'age': [19, 18, 28, 33, 32],
    'bmi': [27.9, 33.77, 33.0, 22.705, 28.88],
    'children': [0, 1, 3, 0, 0]}
)

fig = px.histogram(x = dataset['age'], nbins = 100)
fig.update_layout(xaxis_title = 'age')

buttons = []
for column in dataset.columns:
    buttons.append(
        dict(
            args = [
                {'x': [dataset[column]]},
                {'xaxis.title': column},
                
                # __________________________________
                # I TRIED THIS since fig.layout.figure.data[0].nbinsx = 100
                # {'figure.data[0].nbinsx': 5}
                # __________________________________

            ],
            label = column,
            method = 'update',
        )
    )

fig.update_layout(
    updatemenus = [
        dict(type = 'buttons', buttons = buttons,
             direction = 'right', x=1, y=1.15)
    ],
    title_text = 'Histograms'
)
fig.show()

這是帶有可用按鈕選項的直方圖的外觀。

**當我更改構建直方圖的列時,bin 的數量不會改變。 我該如何解決? 我試過了 **

這是直方圖的圖像! 我還沒有為圖像嵌入贏得聲譽點數。

在此處輸入圖片說明

  • 您尚未定義每列所需的 bin 數量。 已使用col_bins = {c: int(dataset[c].max()-dataset[c].min()) for c in dataset.columns}從您的數據生成值
  • 從風格的角度來看,我使用列表字典推導來構建更新菜單結構
  • 您的代碼很接近,關鍵部分是了解更新方法的參數 這是一個列表,其中第一個元素是字典內更新跡線和第二個元素是一個字典來更新布局。 跟蹤有兩個更新: xnbinsx,因此它們包含在一個字典中
import pandas as pd
import plotly.express as px

dataset = pd.DataFrame(
    {
        "age": [19, 18, 28, 33, 32],
        "bmi": [27.9, 33.77, 33.0, 22.705, 28.88],
        "children": [0, 1, 3, 0, 0],
    }
)
col_bins = {c: int(dataset[c].max()-dataset[c].min()) for c in dataset.columns}

fig = px.histogram(x=dataset["age"], nbins=100)
fig.update_layout(
    updatemenus=[
        {
            "buttons": [
                {
                    "label": c,
                    "method": "update",
                    "args": [{"x": [dataset[c]], "nbinsx":bins}, {"xaxis.title":c}],
                }
                for c, bins in col_bins.items()
            ],
            "direction": "right",
            "type":"buttons",
            "x":1,
            "y":1.15
        }
    ],
    xaxis_title="age",
    title_text = 'Histograms'
)

暫無
暫無

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

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