I'm trying to create a plotly.express
pie chart from data that's in a data table.
The data originates from a Mongo query, and these queries populate the data table.
Using what I have here, the data table works as expected, but I have no pie chart.
Can anyone tell me how to correctly load this data frame for the pie chart?
animal_id
and breed
are the names of two columns in the data frame/data table.
Any help is much appreciated!
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
The source data is loaded into a pandas data frame by querying a MongoDB database
df = pd.DataFrame.from_records(db.collection.find({}))
and this is a sample of one of the db records:
> 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
}
Figured it out. Callback as such:
@app.callback(
Output("pie", "figure"),
[Input("datatable-id", "data")]
)
def generate_chart(data):
dff = pd.DataFrame.from_dict(data)
fig = px.pie(
dff,
names='breed',
)
return fig
I guess values
is implied is the call to px.pie()