GroupBy and plot with pandas

Viewed 83

I have data. There are some groups of people who participate in the meetings. Meetings are divided into speeches. Each meeting and speeches combination has a number of participants. The number of participants in one meeting does not change. In other words, the number of participants only changes from meeting to meeting.

data = [
 ['group_1', 1, 1, 68],
 ['group_2', 1, 1, 35],
 ['group_1', 1, 2, 68],
 ['group_2', 1, 2, 35],
 ['group_1', 2, 1, 78],
 ['group_2', 2, 1, 25],
 ['group_1', 2, 2, 78], 
 ['group_2', 2, 2, 25],
 ['group_1', 3, 1, 73], 
 ['group_2', 3, 1, 30],
 ['group_1', 3, 2, 73], 
 ['group_2', 3, 2, 30]]
df = pd.DataFrame(data, columns=['group_name', 'meeting', 'present', 'members'])

X is meeting, y is number of participants. I want to plot something like this.

df.groupby(['group_name']).plot(
         x='meeting', y='members',
         color='#4b0082', linewidth=3,
         marker='h', markerfacecolor='lightgreen', markeredgewidth=1, markersize=9, markevery=1);

enter image description here

However, I would like to add a title as a group name and sign the y-axis. and I also have a problem when I run this code on all data, for some reason I have extra points on the plot. enter image description here

On the first graph the count should start from meeting 27 and there is an anomaly in meeting area 40. On the second graph there are anomalies in a 27 meeting area.

1 Answers

Since pandas >= 1.1.0 we have the ylabel argument in DataFrame.plot. Also we will rewrite your groupby a bit so we can access the group name:

for grp, d in df.groupby('group_name'):
    d.plot(
        x='meeting',
        y='members',
        color='#4b0082',
        ylabel='members',
        title=grp,
        linewidth=3,
        marker='h',
        markerfacecolor='lightgreen',
        markeredgewidth=1,
        markersize=9,
        markevery=1
    )

plots

Related