Skip to content
Advertisement

Generate BarGraph from DataFrame

So I have a generated a Disease_Data dataframe that has 2 columns, Location and Data (see below).

Location    Data
Alabama     30.675
Alaska      27.3917
Arizona     25.825
Arkansas    29.2
California  29.117
Colorado    35.65

I wanted to generate a bar graph like below:

enter image description here

However, when I tried the code below, things did not work and gave an error: KeyError: ‘Location’

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
Disease_Data_Loc = Disease_Data['Location']
Disease_Data_Value = Disease_Data['Data']
ax.bar(Disease_Data_Loc ,Disease_Data_Value )
plt.show()

Please help, thank you

Advertisement

Answer

  • Just plot the dataframe
import pandas as pd
import matplotlib.pyplot as plt

data = {'Location': ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado'],
        'Data': [30.675, 27.3917, 25.825, 29.2, 29.116999999999997, 35.65]}

df = pd.DataFrame(data)

# plot
df.plot('Location', 'Data', kind='bar', legend=False)
plt.ylabel('Cases')
plt.title('Cases of Disease by State')
plt.show()

enter image description here

Advertisement