Skip to content

Instantly share code, notes, and snippets.

@sinhrks
Created March 16, 2014 03:42
Show Gist options
  • Save sinhrks/9578208 to your computer and use it in GitHub Desktop.
Save sinhrks/9578208 to your computer and use it in GitHub Desktop.
Pandas dataframe bar plot sample with flexible bar width and position
import string
from pandas import DataFrame
import numpy as np
from numpy.random import randn
import pandas.tools.plotting as plotting
from matplotlib.pylab import close
df = DataFrame(randn(6, 4),
index=list(string.ascii_letters[:6]),
columns=['x', 'y', 'z', 'four'])
import matplotlib.pyplot as plt
df1 = df.copy()
df2 = df.drop('x', axis=1)
for df in [df1, df2]:
fig, axes = plt.subplots(3, 4, figsize=(14, 8))
plt.subplots_adjust(top=0.95, bottom=0.05, left=0.05, right=0.95, hspace=0.35)
df.plot(kind='bar', title='Default', ax=axes[0, 0], legend=False)
df.plot(kind='bar', stacked=True, title='Default', ax=axes[0, 1], legend=False)
df.plot(kind='barh', title='Default', ax=axes[0, 2], legend=False)
df.plot(kind='barh', stacked=True, title='Default', ax=axes[0, 3], legend=False)
w = 0.9
title = 'width={0}'.format(w)
df.plot(kind='bar', width=w, title=title, ax=axes[1, 0], legend=False)
df.plot(kind='bar', width=w, stacked=True, title=title, ax=axes[1, 1], legend=False)
df.plot(kind='barh', width=w, title=title, ax=axes[1, 2], legend=False)
df.plot(kind='barh', width=w, stacked=True, title=title, ax=axes[1, 3], legend=False)
p=0.2
title = 'width={0}, pos={1}'.format(w, p)
df.plot(kind='bar', width=w, pos=p, title=title, ax=axes[2, 0], legend=False)
df.plot(kind='bar', width=w, pos=p, stacked=True, title=title, ax=axes[2, 1], legend=False)
df.plot(kind='barh', width=w, pos=p, title=title, ax=axes[2, 2], legend=False)
df.plot(kind='barh', width=w, pos=p, stacked=True, title=title, ax=axes[2, 3], legend=False)
plt.show()
@sinhrks
Copy link
Author

sinhrks commented Mar 16, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment