0

I'm trying to learn how to plot dataframes. I read in a csv and have the following columns:

 cost, model, origin, year
--------------------------
200    x1     usa     2020
145    x1     chn     2020
233    x1     usa     2020
122    x2     chn     2020
583    x2     usa     2020
233    x3     chn     2020 
201    x3     chn     2020

I'm trying to create a bar plot and only want to plot the average cost per model.

Here's my attempt, but I dont think im on the right track:

df = df.groupby('cost').mean()
plt.bar(df.index, df['model'])
plt.show()
2
  • Can you provide an example of the data frame? Commented Apr 5, 2021 at 17:51
  • @RithwikBabu let me know if that helps Commented Apr 5, 2021 at 17:58

2 Answers 2

1

You can groupby model, then calculate the mean of cost and plot it:

df.groupby('model')['cost'].mean().plot.bar()

Output:

picture


Or with seaborn:

sns.barplot(data=df, x='model', y='cost', ci=None)

Output:

picture

Sign up to request clarification or add additional context in comments.

5 Comments

thank you for providing this. So question ontop of this. Lets say theres 100+ models. If i wanted to take the head(20) and sort in descending order. How would i do that?
Sort in descending order by average cost or by the name of the model?
sorry for not specifying. sorting in descending order by average cost!
Sure, you just add .nlargest(20), making it df.groupby('model')['cost'].mean().nlargest(20).plot.bar()
This makes sense. Thank you very much!
1

You can use the pandas plot function like so:

df.plot.bar(x='model', y='cost')

2 Comments

im struggling with plotting the "the average cost per model". How would i get the average/mean?
df.groupby('model')['cost'].mean()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.