0
votes

I plot value counts for two different data frames, but the second data frame is automatically plotted with the wrong x-axis labels. (See the Photo) Is there a way to change the order of the bars in each plot or to make all plots on the figure align by the x-axis labels? Right now, they are only ordering in a descending order, but I need them to order based on the x-axis labels.

In the "df" data frame, their are 158 Females and 140 Males. In my the "signed" data frame, there are 13 Females and 19 Males. When I plot these, the plot shows 140/13 Females and 158/19 Males, when it should show 158/13 females and 140/19 Males. I have been able to use the "ascending" parameter on the value_counts method to reverse the order of the value counts, but this solution will not work for my data frames with more than two different values.

Resulting plot: plot

> df['Gender'].value_counts()

F    158
M    140
Name: Gender, dtype: int64

> signed['Gender'].value_counts()

M    19
F    13
Name: Gender, dtype: int64

df['Gender'].value_counts().plot('bar', position=1, width = width)
signed['Gender'].value_counts().plot('bar', color='skyblue', position=0, width = width)
width = .25
plt.show()

(see photo of plot above)

2
Welcome to SO. Please take the time to read How to Ask and the other links found on that page. There may be more than one way. Dataframe plots are a 'simple wrapper' for Matplotlib.pyplot.plt. You can typically find a feature you want by browsing Matplotlib's gallery It also has excellent Tutorials. which are worth investing time with. - wwii

2 Answers

2
votes

Consider consolidating into a single dataframe by joining two series on Gender index:

import matplotlib
matplotlib.style.use('ggplot')

...
graph_df = df['Gender'].value_counts().rename('df').to_frame()\
               .join(signed['Gender'].value_counts().rename('signed').to_frame())

graph_df.plot(kind='bar',figsize=(8, 4))

Plot Output

1
votes

Use sort_index() after value_counts()

width = .25    
df['Gender'].value_counts().sort_index().plot('bar', position=1, width = width)
signed['Gender'].value_counts().sort_index().plot('bar', color='skyblue', position=0, width = width)
plt.show()