Show Sidebar Hide Sidebar

Bar Chart in matplotlib

How to make a bar chart in matplotlib. Examples of grouped, stacked, overlaid, and colored bar charts.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version Check

Plotly's python package is updated frequently. Run pip install plotly --upgrade to use the latest version.

In [1]:
import plotly
plotly.__version__
Out[1]:
'3.1.1'

Basic Bar Chart

In [2]:
import plotly.plotly as py
import plotly.tools as tls

import matplotlib.pyplot as plt


y = [3, 10, 7, 5, 3, 4.5, 6, 8.1]
N = len(y)
x = range(N)
width = 1/1.5
plt.bar(x, y, width, color="blue")


fig = plt.gcf()
plotly_fig = tls.mpl_to_plotly(fig)
py.iplot(plotly_fig, filename='mpl-basic-bar')
Out[2]:

Bar Using Dictionary

Inspired by Stack Overflow

In [3]:
import plotly.plotly as py
import plotly.tools as tls

import matplotlib.pyplot as plt

dictionary = plt.figure()

D = {u'Label0':26, u'Label1': 17, u'Label2':30}

plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), D.keys())

plotly_fig = tls.mpl_to_plotly(dictionary)
py.iplot(plotly_fig, filename='mpl-dictionary')
Out[3]:

Stacked Bar Chart With Labels

Inspired by Matplotlib Docs

In [4]:
import plotly.plotly as py
import plotly.tools as tls

import matplotlib.pyplot as plt
import numpy as np

mpl_fig = plt.figure()
ax = mpl_fig.add_subplot(111)

N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = ax.bar(ind, menMeans, width, color=(0.2588,0.4433,1.0))
p2 = ax.bar(ind, womenMeans, width, color=(1.0,0.5,0.62),
             bottom=menMeans)
ax.set_ylabel('Scores')
ax.set_xlabel('Groups')
ax.set_title('Scores by group and gender')

ax.set_xticks(ind + width/2.)
ax.set_yticks(np.arange(0, 81, 10))
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))

plotly_fig = tls.mpl_to_plotly( mpl_fig )

# For Legend
plotly_fig["layout"]["showlegend"] = True
plotly_fig["data"][0]["name"] = "Men"
plotly_fig["data"][1]["name"] = "Women"
py.iplot(plotly_fig, filename='stacked-bar-chart')
Out[4]:

Log Bar Plot

Inspired by Matplotlib Docs

In [5]:
import plotly.plotly as py
import plotly.tools as tls

from matplotlib import pylab

log = plt.figure()

data = ((3,1000), (10,3), (100,30), (500, 800), (50,1))

pylab.xlabel("FOO")
pylab.ylabel("FOO")
pylab.title("Testing")
pylab.gca().set_yscale('log')

dim = len(data[0])
w = 0.75
dimw = w / dim

x = pylab.arange(len(data))
for i in range(len(data[0])) :
    y = [d[i] for d in data]
    b = pylab.bar(x + i * dimw, y, dimw, bottom=0.001)
pylab.gca().set_xticks(x + w / 2)
pylab.gca().set_ylim( (0.001,1000))

plotly_fig = tls.mpl_to_plotly(log)
py.iplot(plotly_fig, filename='mpl-log')
Out[5]:

Bar Chart With Dates

Inspired by Stack Overflow

In [6]:
import plotly.plotly as py
import plotly.tools as tls

import matplotlib.pyplot as plt
import numpy as np
import datetime

date = plt.figure()

x = [datetime.datetime(2010, 12, 1, 10, 0),
    datetime.datetime(2011, 1, 4, 9, 0),
    datetime.datetime(2011, 5, 5, 9, 0)]
y = [4, 9, 2]

ax = plt.subplot(111)
ax.bar(x, y, width=10)
ax.xaxis_date()

plotly_fig = tls.mpl_to_plotly(date)
py.iplot(plotly_fig, filename='mpl-date-example')
Out[6]:

Multiple Bars

Inspired by Stack Overflow

In [7]:
import plotly.plotly as py
import plotly.tools as tls

import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime

multiple_bars = plt.figure()

x = [datetime.datetime(2011, 1, 4, 0, 0),
     datetime.datetime(2011, 1, 5, 0, 0),
     datetime.datetime(2011, 1, 6, 0, 0)]
x = date2num(x)

y = [4, 9, 2]
z=[1,2,3]
k=[11,12,13]

ax = plt.subplot(111)
ax.bar(x-0.2, y,width=0.2,color='b',align='center')
ax.bar(x, z,width=0.2,color='g',align='center')
ax.bar(x+0.2, k,width=0.2,color='r',align='center')
ax.xaxis_date()

plotly_fig = tls.mpl_to_plotly(multiple_bars)
py.iplot(plotly_fig, filename='mpl-multiple-bar')
Out[7]:

Multiple Colors

In [8]:
import plotly.plotly as py
import plotly.tools as tls

import matplotlib.pyplot as plt
import numpy as np


mpl_fig = plt.figure()
ax = mpl_fig.add_subplot(111)

N = 5
ind = np.arange(N)
width = 0.3
vals = [1,2,3,4,5]
colors = ['b','r','g','g','g']
barlist = ax.bar(ind, vals, width)

barlist[0].set_color('g')
barlist[1].set_color('b')

plotly_fig = tls.mpl_to_plotly( mpl_fig )

plotly_fig["data"][0]["marker"]["color"] = ["rgb(255,0,0)",
                                            "rgb(0,255,0)",
                                            "rgb(0,0,0,255)",
                                            "rgb(122,122,122)",
                                            "rgb(0,122,122)"]
py.iplot(plotly_fig, filename='bars-with-multiple-colors')
Out[8]:

Reference

See https://plot.ly/python/reference/ for more information and chart attribute options!

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.