Creating a filled barchart with matplotlib

barchart.png

This a tutorial is to make a filled bar chart with color-fill mapped to data. The chart was created for this project.

Data used for plotting G_perfomance is a pandas dataframe:

State Boy Girl diff Boys_better
JH 38.335000 35.1925 3.142500 True
BR 35.000000 37.0000 2.000000 True
UK 34.965000 33.6750 1.290000 True
UP 44.365000 43.3350 1.030000 True

Step: 1

Import matplotlib

import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib.cm import bwr as cmap
import matplotlib.patches as mpatches

Step: 2

Defining a color scheme and mapping max and min value of variable to fill attribute.

colors.Power takes the max and min value from a column and spit out a value in range [0,1].

​​​ c​map maps the data value to a corresponding color and store in _COLORS

There are other functions such as Normalize (linear scale in range [0,1]) LogNorm (log scale in range [0,1])

cmap is a color map which takes the value in interval [0,1] and gives a color. matplotlib gives a variety of color schemes.

# setting  figure size
plt.figure(figsize=(12,5))

# setting colors. Maps the max and min values
# in "diff" to a color map bwr.
c_normal = colors.PowerNorm(1,vmin=min(G_perfomance["diff"]),vmax=max(G_perfomance["diff"]))
_COLORS = cmap(c_normal(G_perfomance["diff"]))

Step: 3

 A bar plot with color variable points to _COLORS

plt.bar(np.arange(len(G_perfomance["diff"])),
 height = G_perfomance["diff"], width = 0.75, align = "center", color=_COLORS)
plt.xticks(np.arange(len(G_perfomance.index)),list(G_perfomance.index))
plt.axhline(0, color='k', linewidth = 0.5)
plt.xlabel("State")
plt.ylabel("Median Performance Difference\n(Boys - Girls)")

Two patches are added as legend

# creating legend patches
red_patch = mpatches.Patch(color='red', label='Boys Perform Better')
blue_patch = mpatches.Patch(color='blue', label='Girls Perform Better')
plt.legend(handles=[red_patch, blue_patch], loc=4)

plt.show()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s