简体   繁体   中英

In Python is there a way to create a bar chart based on the first column in a two-column groupby table?

I want to create a bar chart based on the first column in a two-column groupby table. I've summed up my dataframe by applying groupby to create the table I want. My groupby table currently only has two columns, the first being the categories, and the second being the count of those categories from my dataframe. I'd like to create a bar chart with plotly express using the first column as the x-axis, and then second column as the y-axis. However, when I applied groupby to the dataframe it grouped my data how I want but that the first column doesn't have a label. In order to create a bar chart I need to tell plotly what the x-axis will be but there's no label in the groupby table.

This is what I currently have for my groupby table:

# Selection list

department = df['Provider Type'].unique().tolist()

departments_selection = st.multiselect('Program:',
                                        department,
                                        default=department)

# Filter dataframe based on selection

mask = df['Provider Type'].isin(departments_selection)
number_of_result = df[mask].shape[0]
st.markdown(f'*Available Results: {number_of_result}*')

## Booked
df_grouped = df[mask].groupby(['Provider Type'])['Provider Type'].count()
st.dataframe(df_grouped)

This is the output, which is what I want: 在此处输入图像描述

As you can see the first column has no label so I can't reference it when trying to create a bar chart. So I end up getting a bar chart with just numbers as labels when I'd really just like to use the first column's categories as labels. This is what I have:

# Bar chart
pie_chart = px.bar(df_grouped,
                x="Provider Type",
                y='Provider Type',
                template='plotly_white')

st.plotly_chart(pie_chart)

This is the output: 在此处输入图像描述

Can someone help me fix my x-axis so it shows the categories like in my groupby table? I'm just not sure how to tell it to look for that first column since it has no label.

You can pass to px.bar for the x argument df_grouped.index .

Because no data was presented in the question i can't do the group by but this code example should show you how to fix the x-axis labels:

import pandas as pd
import plotly.express as px


d = {'Provider Type': [340, 861, 446, 148, 1484, 953, 347, 615]}
index = ['Community Health navigation', 'Dietitian', 'Kinesiology', 
         'MH Navigation', 'MH Therapist', 'Nursing', 'Pharmacist', 'Specialist']
df = pd.DataFrame(data=d, index=index)

fig = px.bar(df, y='Provider Type', x=df.index)
fig.show()

Output:

输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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