Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting from Pivot Table using Pandas

Let's say that I have the following pivot table (this is the one created in the documentation):

In [8]: tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
...:                 'foo', 'foo', 'qux', 'qux'],
...:                ['one', 'two', 'one', 'two',
...:                 'one', 'two', 'one', 'two']]))
...: 

In [9]: index = MultiIndex.from_tuples(tuples, names=['first', 'second'])

In [10]: df = DataFrame(randn(8, 2), index=index, columns=['A', 'B'])

In [11]: df2 = df[:4]

In [12]: df2
Out[12]: 
                     A         B
first second                    
bar   one     0.721555 -0.706771
      two    -1.039575  0.271860
baz   one    -0.424972  0.567020
      two     0.276232 -1.087401

How can I use this table to plot both 'bar' and 'baz' on the same plot with axes (second, A) (i.e. I want to create a plot with the points (one, 0.72), (two, -1.039), (one, -0.42), (two, 0.276), where the first two points are plotted in a different color than the latter two).

I tried using

df2[[0]].plot() 

but this plots the points sequentially on the x-axis so that they are ordered ((bar,one), .721), ((bar,two), -1.039), etc, rather than having the two 'one' points and the two 'two' points share a vertical axis.

like image 531
user3307240 Avatar asked Oct 07 '14 17:10

user3307240


People also ask

Can you make graphs out of pivot tables?

Create a chart from a PivotTable Select a cell in your table. Select PivotTable Tools > Analyze > PivotChart. Select a chart. Select OK.

How do I convert a pivot table into a DataFrame?

The pivot_table() function is used to create a spreadsheet-style pivot table as a DataFrame. The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame.

How do I extract data from a pivot table in Python?

We can use aggfunc and np. sum to get the count or a sum for the cost column automatically by using it as an argument in pivot_table()method. The aggfunc argument can take list of functions. We can compute the mean using numpy and len to get the count.

Can pandas generate graphics plots?

Initializing the Plots ObjectPlotting can be performed in pandas by using the “. plot()” function. This function directly creates the plot for the dataset. This function can also be used in two ways.


1 Answers

Ok, I figured it out. The key was unstacking the data first:

import matplotlib.pyplot as plt

t=df2.unstack(level=0)
plt.plot(t[[0]], color='red')
plt.plot(t[[1]], color='blue')
plt.xticks(range(2), ['one','two'], size='small')

plt.show()
like image 176
user3307240 Avatar answered Oct 13 '22 14:10

user3307240