Reputation: 33
I create a pivot table and I want create a bar graph. This is my pivot_table:
I don't know how to extract the values of the column 1970 and use this information to make a bar graph.
Upvotes: 0
Views: 2526
Reputation: 3594
Just convert dataframe column names to str
then you can select the data of year 1970
with df['1970']
. Then, you can use pandas
built-in plot.bar
method to make a bar plot. Try this:
import pandas as pd
import matplotlib.pyplot as plt
#converting column names to string
df.columns = df.columns.astype(str)
#plotting a bar plot
df['1970'].plot.bar()
plt.show()
Examples based on @AlanDyke DataFrame:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame([[1970,'a',1],
[1970,'b',2],
[1971,'a',2],
[1971,'b',3]],
columns=['year','location', 'value'])
df = pd.pivot_table(df, values='value', index='location', columns='year')
df.columns = df.columns.astype(str)
df['1970'].plot.bar()
plt.show()
Upvotes: 1
Reputation: 914
you can use plt.bar and slice the dataframe:
df = pd.DataFrame([[1970,'a',1],
[1970,'b',2],
[1971,'a',2],
[1971,'b',3]],
columns=['year','location', 'value'])
df = pd.pivot_table(df, values='value', index='location', columns='year')
plt.bar(list(df.transpose().columns), height=df[1970])
Upvotes: 1