Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

python - Using bar graph to present a data from csv file

Suppose I have this csv file:

CODE     AGE GROUP     SEX     CITY      
----     ---------     ---     ----      
E101      25 to 29      M      Denver     
E102      25 to 29      F      Denver       
E105      25 to 29      M      Denver 

I wish to present it using a bar graph but I'm not sure how to count the number of males and females in it. This is what I've coded so far:

import matplotlib.pyplot as plt

plt.style.use('bmh')

x = df['SEX']
y = # what should I put here?

plt.xlabel('Sex', fontsize=16)
plt.ylabel('Number of people', fontsize=16)
plt.bar(x, y)

What should I put in "y" for it to count the number of males and females in the data?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the dataframe plot method like this: df["SEX"].value_counts().plot(kind="bar")

Otherwise, plt.bar() is expecting a list as long as the number of groups (0, 1) for x and the associated counts (2, 1) for y. It’s a bit harder to make sure the labels and counts align this way so I suggest the dataframe method. Your solution does not provide the correct value for x.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...