Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot a vertical area plot with pandas

Is there a straight forward way to plot an area plot using pandas, but orient the plot vertically?

for example to plot an area plot horizontally I can do this:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot(kind='area');

enter image description here

I can plot a bar plot vertically with 'barh'

df.plot(kind='barh');

enter image description here

But I can't figure out a straightforward way to get a area plot vertical

like image 707
johnchase Avatar asked Jun 11 '18 16:06

johnchase


People also ask

How do I plot specific columns in pandas?

Pandas has a tight integration with Matplotlib. You can plot data directly from your DataFrame using the plot() method. To plot multiple data columns in single frame we simply have to pass the list of columns to the y argument of the plot function.

How do you plot area in Python?

Area plot is drawn using the plot member of the DataFrame. If True is specified for the Boolean parameter stacked, area() draws a stacked area plot. It is the default behavior for the area() method. To make an unstacked or overlapped area plot, the stacked parameter should be given the Boolean value "False".


1 Answers

The reason pandas does not provide a vertical stack plot is that matplotlib stackplot is only for horizontal stacks.

However, a stackplot is nothing but a filled lineplot in the end. So you would get the desired plot by plotting the data with fill_betweenx().

import pandas as pd
import numpy as np; np.random.rand(42)
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])

fig, ax = plt.subplots()

data = np.cumsum(df.values, axis=1)
for i, col in enumerate(df.columns):
    ax.fill_betweenx(df.index, data[:,i], label=col, zorder=-i)
ax.margins(y=0)
ax.set_xlim(0, None)
ax.set_axisbelow(False)

ax.legend()


plt.show()

enter image description here

like image 109
ImportanceOfBeingErnest Avatar answered Oct 07 '22 05:10

ImportanceOfBeingErnest