1

I am trying to make a simple bar graph out of a 2 column CSV file. One column is the x axis names, the other column is the actual data which will be used for the bars. The CSV looks like this:

count,team
21,group1
15,group2
63,group3
22,group4
42,group5
72,group6
21,group7
23,group8
24,group9
31,group10
32,group11

I am using this code:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.read_csv("sampleData.csv",sep=",").set_index('count')

d = dict(zip(df.index,df.values.tolist()))

df.plot.bar(x = 'count', y = 'team')

print(d)

However, I get an error

KeyError: 'count' from this line : df.plot.bar(x = 'count', y = 'team')

I don't understand how there is an error for something that exists.

1 Answer 1

2

When you set the count as index, you just have a single column left in your DataFrame, i.e., team. Don't set the count as index and switch the order of x and y values for plotting the bar chart

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.read_csv("sampleData.csv", sep=",")
df.plot.bar(x = 'team', y = 'count')

enter image description here

Matplotlib solution

plt.bar(df['team'], df['count']) 
plt.xticks(rotation=45) # Just rotating for better visualizaton
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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