数据框中的饼图

2024-06-17 08:48:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从数据表中的数据创建plotly.express饼图。
数据来自Mongo查询,这些查询填充数据表。
使用这里的数据表,数据表按预期工作,但我没有饼图。
谁能告诉我如何正确加载饼图的数据框

animal_idbreed是数据帧/数据表中两列的名称

非常感谢您的帮助

dash_table.DataTable(
    id='datatable-id',
    columns=[
        {"name": i, "id": i, "deletable": False, "selectable": True} for i in df.columns
    ],
    data=df.to_dict('records'),
    editable=False,
    filter_action="native",
    sort_action="native",
    sort_mode="multi",
    column_selectable=False,
    row_selectable="single",
    row_deletable=False,
    selected_rows=[],
    page_action="native",
    page_current=0,
    page_size=10
),

html.Div(
    dcc.Graph(
        id="pie-chart"
    )
)

@app.callback(
    Output("pie-chart", "figure"),
    [Input("datatable-id", "data")]
)
def generate_chart(data):
    dfc = pd.DataFrame(list(data))

    fig = px.pie(dfc, values='animal_id', names='breed')

    return fig

通过查询MongoDB数据库,将源数据加载到pandas数据帧中

df = pd.DataFrame.from_records(db.collection.find({}))

这是一个db记录的样本:

> db.collection.findOne()
{
    "_id" : ObjectId("5fccfabbfb3f7580efe722cd"),
    "" : 1,
    "age_upon_outcome" : "3 years",
    "animal_id" : "A746874",
    "animal_type" : "Cat",
    "breed" : "Domestic Shorthair Mix",
    "color" : "Black/White",
    "date_of_birth" : "2014-04-10",
    "datetime" : "2017-04-11 09:00:00",
    "monthyear" : "2017-04-11T09:00:00",
    "name" : "",
    "outcome_subtype" : "SCRP",
    "outcome_type" : "Transfer",
    "sex_upon_outcome" : "Neutered Male",
    "location_lat" : 30.5066578739455,
    "location_long" : -97.3408780722188,
    "age_upon_outcome_in_weeks" : 156.767857142857
}

Tags: 数据idfalsedfdatachartpageaction