Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Bar Plot using Subplots

Tags:

pandas

plot

I am using pandas to create bar plot. Here is an example:

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

I want to plot two subplots within a figure and have a and b on one bar plot and c and d on another. How do I go about this?

Further, if I wanted to include the two subplots with another subplot but not created by pandas, how to do that? So a 3x1 figure where two of the subplots are from the data frame using pandas and one without using pandas. Example Plot

Taking a second attempt at this but with some modifications.

df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
x=[1,2,3,4,5]
y=[1,4,9,16,25]

fig, axes = plt.subplots(figsize=(8,8),nrows=2, ncols=2)
ax1=plt.subplot(2,2,1)
plt.plot(x,y)

#ax2=plt.subplot(2,2,2)
df["b"].plot(ax=axes[0,1], kind='bar', grid=True)
df["c"].plot(ax=axes[1,0], kind='bar', grid=True)
df["d"].plot(ax=axes[1,1], kind='bar', grid=True)

ax1.grid(True)
ax1.set_ylabel('Test')
ax1.set_xlabel('Test2')

#ax2.set_ylabel('Test')

How do I add axes labels for the bar plots in my subplots? Notice I have commented out ax2=plt.subplot(2,2,2) as I was testing this but this erases the bar plot completely and add the labels. Why does it do that and how can I get around this? Below is the output with the ax2... un-commented.

Plot with the lines un-commented

like image 971
Charanjit Pabla Avatar asked Jun 14 '18 18:06

Charanjit Pabla


People also ask

What is Panda rot?

rot : This keyword argument allows to rotate the markings on the x axis for a horizontal plotting and y axis for a vertical plotting. fontsize : Allows to set the font size for the labels and axis points. colormap : This keyword argument allows to choose different colour sets for the plots.


1 Answers

You can start to play from this:

%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

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

fig, axes = plt.subplots(nrows=1, ncols=2)
df[["a","b"]].plot(ax=axes[0], kind='bar')
df[["c", "d"]].plot(ax=axes[1], kind='bar');

Then you can have a look at this

like image 124
rpanai Avatar answered Oct 11 '22 12:10

rpanai