Create a graph of a pivot_table

Question:

I create a pivot table and I want create a bar graph. This is my pivot_table:

Information

I don’t know how to extract the values of the column 1970 and use this information to make a bar graph.

Asked By: Adrian Cancino

||

Answers:

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])
Answered By: Alan Dyke

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()

enter image description here

Answered By: Grayrigel
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.