In [120]:
#this line prepares IPython for working with matplotlib
%matplotlib inline  

# # this actually imports matplotlib
# import numpy as np
# import matplotlib.pyplot as plt  

# x = np.linspace(0, 10, 30)  #array of 30 points from 0 to 10
# y = np.sin(x)
# z = y + np.random.normal(size=30) * .2
# plt.plot(x, y, 'b+:', label='A sine wave')
# #plt.axhspan(0, 0.25, 0, 1, hold=None, hatch='/')
# plt.axvline(x=3, ymin=0, ymax=1, hold=None,linewidth=4, color='r')
# #plt.axvspan(0, 5, 0, 1, hold=None)
# plt.bar(0, 0.25, width=1, bottom=None, hold=None, data=None)
# #plt.plot(x, z, 'b-', label='Noisy sine')
# plt.legend(loc = 'lower right')
# plt.xlabel("X axis")
# plt.ylabel("Y axis")
# plt.show()

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.set_ylim(0, 50)
ax.set_xlim(0, 200)


#ax.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9),
#               facecolors=('red', 'yellow', 'green'))



ax.set_xlabel('seconds since start')
ax.set_ylabel('Simulation')

ax.set_yticks([5,15, 25])
ax.set_yticklabels(['S1','S2', 'S3'])


bars_collection_xx =[(100, 20),(150, 10)]
bars_collection_yy = (25,5)
for xx in bars_collection_xx:
    print xx,bars_collection_yy
    ax.broken_barh([xx], bars_collection_yy, facecolors='red',hatch='xxx')


bars_collection_xx =[(100, 20),(150, 10)]
bars_collection_yy = (5,5)
for xx in bars_collection_xx:
    print xx,bars_collection_yy
    ax.broken_barh([xx], bars_collection_yy, facecolors='red',hatch='xxx')


bars_collection_xx =[(100, 20),(150, 10)]
bars_collection_yy = (15,5)
for xx in bars_collection_xx:
    print xx,bars_collection_yy
    ax.broken_barh([xx], bars_collection_yy, facecolors='red',hatch='xxx')


    
    
#ax.broken_barh([(100, 10), (150, 10)], (25, 5), facecolors='red',hatch='xxx')

#ax.broken_barh([(100, 10), (150, 10)], (5, 5), facecolors='blue',hatch='xxx')

#ax.broken_barh([(100, 10), (150, 10)], (15, 5), facecolors='green',hatch='xxx')


plt.axvline(x=10, ymin=0, ymax=1, hold=None)

ax.grid(True)

ax.annotate('race interrupted', (61, 25),
            xytext=(0.8, 0.9), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            fontsize=16,
            horizontalalignment='right', verticalalignment='top')

xposition = [20, 50, 100]

for xc in xposition:
    plt.axvline(x=xc, color='r', linestyle='-')

yposition = [5, 15, 25]
for yc in yposition:
    plt.axhline(y=yc, color='b', linestyle='-')
    
plt.show()


(100, 20) (25, 5)
(150, 10) (25, 5)
(100, 20) (5, 5)
(150, 10) (5, 5)
(100, 20) (15, 5)
(150, 10) (15, 5)

In [121]:
import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
ax1.tick_params('y', colors='b')

ax2 = ax1.twinx()
s2 = np.sin(2 * np.pi * t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
ax2.tick_params('y', colors='r')

fig.tight_layout()
plt.show()



In [123]:
import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows=3)

colors = ('k', 'r', 'b')
for ax, color in zip(axes, colors):
    data = np.random.random(1) * np.random.random(10)
    ax.plot(data, marker='*', linestyle='none', color=color)

plt.show()


You can share the x or y axis limits for one axis with another by passing an axes instance as a sharex or sharey kwarg.

Changing the axis limits on one axes will be reflected automatically in the other, and vice-versa, so when you navigate with the toolbar the axes will follow each other on their shared axes. Ditto for changes in the axis scaling (e.g., log vs linear). However, it is possible to have differences in tick labeling, e.g., you can selectively turn off the tick labels on one axes.

The example below shows how to customize the tick labels on the various axes. Shared axes share the tick locator, tick formatter, view limits, and transformation (e.g., log, linear). But the ticklabels themselves do not share properties. This is a feature and not a bug, because you may want to make the tick labels smaller on the upper axes, e.g., in the example below.

If you want to turn off the ticklabels for a given axes (e.g., on subplot(211) or subplot(212), you cannot do the standard trick

setp(ax2, xticklabels=[])

because this changes the tick Formatter, which is shared among all axes. But you can alter the visibility of the labels, which is a property

setp( ax2.get_xticklabels(), visible=False)


In [124]:
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.01, 5.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.exp(-t)
s3 = np.sin(4*np.pi*t)

ax1 = plt.subplot(311)
plt.plot(t, s1)
plt.setp(ax1.get_xticklabels(), fontsize=6)

# share x only
ax2 = plt.subplot(312, sharex=ax1)
plt.plot(t, s2)
# make these tick labels invisible
plt.setp(ax2.get_xticklabels(), visible=False)

# share x and y
ax3 = plt.subplot(313, sharex=ax1, sharey=ax1)
plt.plot(t, s3)
plt.xlim(0.01, 5.0)
plt.show()



In [135]:
import matplotlib.pyplot as plt
# plot a line, implicitly creating a subplot(111)
#plt.plot([1,2,3])
# now create a subplot which represents the top plot of a grid
# with 2 rows and 1 column. Since this subplot will overlap the
# first, the plot (and its axes) previously created, will be removed
plt.subplot(211)
plt.plot([1,2,1])
plt.subplot(212) # creates 2nd subplot with yellow background
plt.setp(plt.subplot(212).get_xticklabels(), visible=False)
plt.show()



In [148]:
import matplotlib.pyplot as plt
# plot a line, implicitly creating a subplot(111)
#plt.plot([1,2,3])
# now create a subplot which represents the top plot of a grid
# with 2 rows and 1 column. Since this subplot will overlap the
# first, the plot (and its axes) previously created, will be removed
ax = plt.subplot(111)

#plt.plot([1,2,1])

ax.set_xlim([0, 200])
ax.set_ylim([0, 50])

bars_collection_xx =[(00, 100),(150, 50)]
bars_collection_yy = (15,5)
for xx in bars_collection_xx:
    print xx,bars_collection_yy
    ax.broken_barh([xx], bars_collection_yy, facecolors='g',hatch='xxx')

plt.annotate('This is awesome!', 
             xy=(100, 20),  
             xycoords='data',
             textcoords='offset points',
             arrowprops=dict(arrowstyle="<->"))    
    
    
#plt.setp(plt.subplot(111).get_xticklabels(), visible=False)
#plt.setp(plt.subplot(111).get_yticklabels(), visible=False)


plt.show()


(0, 100) (15, 5)
(150, 50) (15, 5)

In [155]:
import matplotlib.pyplot as plt

plt.figure(figsize=(3,2))
ax=plt.axes([0.1, 0.1, 0.8, 0.7])
an1 = ax.annotate("Test 1", xy=(0.5, 0.5), xytext=(0.2,0.8), xycoords="data",
                  va="center", ha="center", arrowprops=dict(facecolor='black', shrink=0.05),
                  bbox=dict(boxstyle="round", fc="w"))





from matplotlib.text import OffsetFrom

offset_from = OffsetFrom(an1, (0.5, 0))

# an2 = ax.annotate("Test 2", xy=(0.1, 0.1), xycoords="data",
#                   xytext=(0, -10), textcoords=offset_from,
#                   # xytext is offset points from "xy=(0.5, 0), xycoords=an1"
#                   va="top", ha="center",
#                   bbox=dict(boxstyle="round", fc="w"),
#                   arrowprops=dict(arrowstyle="<->"))
plt.show()



In [186]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')
ax2.add_patch(
    patches.Rectangle(
        (0.1, 0.1),
        0.1,
        0.2,
        fill=False      # remove background
    )
)

ax2.annotate('', xy=(0, 0.5), xycoords='axes fraction', xytext=(0.6, 0.5), 
            arrowprops=dict(arrowstyle="<->", color='b'))


Out[186]:
<matplotlib.text.Annotation at 0x7f87318cced0>

In [157]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch()
ax1.add_patch(
    patches.Rectangle(
        (0.1, 0.1),   # (x,y)
        0.5,          # width
        0.5,          # height
    )
)
plt.show()
#fig1.savefig('rect1.png', dpi=90, bbox_inches='tight')



In [199]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')
ax2.add_patch(
    patches.Rectangle(
        (0.1, 0.1),
        0.5,
        0.5,
        fill=False      # remove background
    )
)

ax2.annotate('', xy=(0, 0.5), xycoords='axes fraction', xytext=(1, 0.5), 
            arrowprops=dict(arrowstyle="<->", color='b'))

el = Ellipse((2, -1), 0.5, 0.5)

ann = ax2.annotate('Test',
                  xy=(.2, 0.2), xycoords='data',
                  xytext=(55, 0), textcoords='offset points',
                  size=20, va="center",
                  bbox=dict(boxstyle="round", fc=(1.0, 0.7, 0.7), ec="none"),
                  arrowprops=dict(arrowstyle="wedge,tail_width=1.",
                                  fc=(1.0, 0.7, 0.7), ec="none",
                                  patchA=None,
                                  patchB=el,
                                  relpos=(0.2, 0.5)))
bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="cyan", ec="b", lw=2)
t = ax2.text(0, 0, "Direction", ha="center", va="center", rotation=40,
            size=15,
            bbox=bbox_props)


plt.show()
#fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')



In [160]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig3 = plt.figure()
ax3 = fig3.add_subplot(111, aspect='equal')
for p in [
    patches.Rectangle(
        (0.1, 0.1), 0.3, 0.6,
        hatch='/'
    ),
    patches.Rectangle(
        (0.5, 0.1), 0.3, 0.6,
        hatch='\\',
        fill=False
    ),
]:
    ax3.add_patch(p)
    
    
#fig3.savefig('rect3.png', dpi=90, bbox_inches='tight')



In [161]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

patterns = ['-', '+', 'x', 'o', 'O', '.', '*']  # more patterns
fig4 = plt.figure()
ax4 = fig4.add_subplot(111, aspect='equal')
for p in [
    patches.Rectangle(
        (0.05 + (i * 0.13), 0.1),
        0.1,
        0.6,
        hatch=patterns[i],
        fill=False
    ) for i in range(len(patterns))
]:
    ax4.add_patch(p)



In [162]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig5 = plt.figure()
ax5 = fig5.add_subplot(111, aspect='equal')
for p in [
    patches.Rectangle(
        (0.03, 0.1), 0.2, 0.6,
        alpha=None,
    ),
    patches.Rectangle(
        (0.26, 0.1), 0.2, 0.6,
        alpha=1.0
    ),
    patches.Rectangle(
        (0.49, 0.1), 0.2, 0.6,
        alpha=0.6
    ),
    patches.Rectangle(
        (0.72, 0.1), 0.2, 0.6,
        alpha=0.1
    ),
]:
    ax5.add_patch(p)



In [163]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig6 = plt.figure()
ax6 = fig6.add_subplot(111, aspect='equal')
for p in [
    patches.Rectangle(
        (0.03, 0.1), 0.2, 0.6,
        facecolor=None      # Default
    ),
    patches.Rectangle(
        (0.26, 0.1), 0.2, 0.6,
        facecolor="none"     # No background
    ),
    patches.Rectangle(
        (0.49, 0.1), 0.2, 0.6,
        facecolor="red"
    ),
    patches.Rectangle(
        (0.72, 0.1), 0.2, 0.6,
        facecolor="#00ffff"
    ),
]:
    ax6.add_patch(p)



In [164]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig8 = plt.figure()
ax8 = fig8.add_subplot(111, aspect='equal')
for p in [
    patches.Rectangle(
        (0.03, 0.1), 0.2, 0.6, fill=False,
        linewidth=None      # Default
    ),
    patches.Rectangle(
        (0.26, 0.1), 0.2, 0.6, fill=False,
        linewidth=0
    ),
    patches.Rectangle(
        (0.49, 0.1), 0.2, 0.6, fill=False,
        linewidth=0.5
    ),
    patches.Rectangle(
        (0.72, 0.1), 0.2, 0.6, fill=False,
        linewidth=3
    ),
]:
    ax8.add_patch(p)



In [165]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig9 = plt.figure()
ax9 = fig9.add_subplot(111, aspect='equal')
for p in [
    patches.Rectangle(
        (0.03, 0.1), 0.2, 0.6, fill=False,
        linestyle='solid'   # Default
    ),
    patches.Rectangle(
        (0.26, 0.1), 0.2, 0.6, fill=False,
        linestyle='dashed'
    ),
    patches.Rectangle(
        (0.49, 0.1), 0.2, 0.6, fill=False,
        linestyle='dashdot'
    ),
    patches.Rectangle(
        (0.72, 0.1), 0.2, 0.6, fill=False,
        linestyle='dotted'
    ),
]:
    ax9.add_patch(p)



In [167]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

n = 5
data1 = np.array(range(n)) + np.random.rand(n)
data2 = (np.array(range(n)) + np.random.rand(n)) / 2

fig, ax = plt.subplots(2)

bar_width = 0.4  # default: 0.8
bar_locations = np.arange(n)

ax[0].bar(bar_locations, data1, bar_width)
ax[0].bar(
	bar_locations - bar_width, 
	data2, 
	bar_width, 
	color='r'
)

ax[1].bar(bar_locations, data1, bar_width)
ax[1].bar(
	bar_locations - (bar_width / 2), 
	data2, bar_width, 
	color='r'
)

fig.show()



In [169]:
import matplotlib.pyplot as plt
import numpy as np

n = 5
data = np.array(range(n)) + np.random.rand(n)

fig, ax = plt.subplots()

bar_locations = np.arange(n)
ax.barh(bar_locations, data)
plt.show()


Set the bar width for a plot with matplotlib


In [172]:
import matplotlib.pyplot as plt
import numpy as np

n = 5
data = np.array(range(n)) + np.random.rand(n)

fig, ax = plt.subplots()

bar_width = 0.5  # default: 0.8
bar_locations = np.arange(n)
ax.bar(bar_locations, data, bar_width)

plt.show()



In [173]:
import matplotlib.pyplot as plt
import numpy as np

n = 5
data = np.array(range(n)) + np.random.rand(n)

fig, ax = plt.subplots(4, figsize=(6, 12))

bar_locations = np.arange(n)
ax[0].bar(bar_locations, data)
ax[1].bar(bar_locations, data, color='red')

ax[2].bar(bar_locations, data, color=['red', 'blue'])

colors = ['#624ea7', 'g', 'yellow', 'k', 'maroon']

ax[3].bar(bar_locations, data, color=colors)
plt.show()



In [181]:
%matplotlib inline
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Nicolas P. Rougier. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8,5), dpi=80)
ax = plt.subplot(111)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-",  label="sine")

plt.xlim(X.min()*1.1, X.max()*1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
           [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.ylim(C.min()*1.1,C.max()*1.1)
plt.yticks([-1, +1],
           [r'$-1$', r'$+1$'])

t = 2*np.pi/3
plt.plot([t,t],[0,np.cos(t)],
         color ='blue',  linewidth=1.5, linestyle="--")
plt.scatter([t,],[np.cos(t),], 50, color ='blue')
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
             xy=(t, np.sin(t)),  xycoords='data',
             xytext=(+10, +30), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

plt.plot([t,t],[0,np.sin(t)],
         color ='red',  linewidth=1.5, linestyle="--")
plt.scatter([t,],[np.sin(t),], 50, color ='red')
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
             xy=(t, np.cos(t)),  xycoords='data',
             xytext=(-90, -50), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="<->", connectionstyle="arc3,rad=.2"))

plt.legend(loc='upper left', frameon=False)


Out[181]:
<matplotlib.legend.Legend at 0x7f8731f9ae90>

In [205]:
import matplotlib.pyplot as plt

ax = plt.axes()
ax.arrow(0, 0, 0.2, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k',linestyle='--')
plt.show()



In [209]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig12 = plt.figure()
ax12 = fig12.add_subplot(111, aspect='equal')

# More styles:
styles = ['<-', '<->', '-', '-|>', '<|-', '<|-|>', '-[', ']-', ']-[', 'fancy']

for p in [
    patches.FancyArrowPatch(
        (0.02 + i * 0.1, 0.2),
        (0.02 + i * 0.1, 0.8),
        arrowstyle=styles[i],
        mutation_scale=20
    ) for i in range(len(styles))
]:
    ax12.add_patch(p)