In [3]:
%matplotlib inline #Set this to show plots in ipy notebook

Simple Plots


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

matplotlib.__version__

#Prepare some data
x = np.random.normal(0,1.0/3.0,1000)
y = np.random.normal(0,1.0/3.0,1000)
heatmap, xedges, yedges = np.histogram2d(-y, x, bins=[20, 20])
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

#Generate a figure with two axes, next to each other
fig = plt.figure(figsize=(9, 4))  # Size in inches
axLeft = fig.add_subplot(121)
axRight = fig.add_subplot(122)

#Plot scattering plot left
axLeft.set_title('Scatter plot')
axLeft.scatter(x, y)
axLeft.set_xlim(xedges[0], xedges[-1])
axLeft.set_ylim(yedges[0], yedges[-1])

#Plot histogram right
axRight.imshow(heatmap, extent=extent, interpolation='none')
axRight.set_title('Histogram plot')
axRight.set_axis_off()
axRight.set_xlim(xedges[0], xedges[-1])
axRight.set_ylim(yedges[0], yedges[-1])

plt.show()


Note: Be aware that the plots look mirrored as the histogram is a matrix, that has its origin in the upper left corder, with the y axis going down, where the Scatter plot has its origin in the center, with the y-Axis going up! In order to make the look the same one has to invert the y-Axis of the scatter plot.

Annotations and Text

Now add some nice text using annoteate() and text()


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

matplotlib.__version__

#Prepare some data
x = np.random.normal(0,1.0/3.0,1000)
y = np.random.normal(0,1.0/3.0,1000)
heatmap, xedges, yedges = np.histogram2d(-y, x, bins=[20, 20])
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

#Generate a figure with two axes, next to each other
fig = plt.figure(figsize=(9, 4))  # Size in inches
axLeft = fig.add_subplot(121)
axRight = fig.add_subplot(122)

#Plot scattering plot left
axLeft.set_title('Scatter plot')
axLeft.scatter(x, y)
axLeft.set_xlim(xedges[0], xedges[-1])
axLeft.set_ylim(yedges[0], yedges[-1])

#Plot histogram right
axRight.imshow(heatmap, extent=extent, interpolation='none')
axRight.set_title('Histogram plot')
axRight.set_axis_off()
axRight.set_xlim(xedges[0], xedges[-1])
axRight.set_ylim(yedges[0], yedges[-1])

#Add some annotations
axLeft.annotate('The Center(0, 0)', xy=(0.0, 0.0),  xycoords='data',
                    xytext=(-300, 30), textcoords='offset points', color='y', fontsize=18,
                    arrowprops=dict(arrowstyle="->", color='y'))                           
                                                                                
axRight.annotate('The Center\n(0, 0)', xy=(0, 0),  xycoords='data',          
                 xytext=(200, 30), textcoords='offset points', color='#CF21CC', fontsize=18,
                 arrowprops=dict(arrowstyle="fancy", color='#CF21CC', linewidth=1))
                                                                                                                                                               
fig.text(0.5, 0.3, 'Hello Bob', color='r', fontsize=20, rotation='vertical')    
plt.show()


For all kind of arrow styles and other annotation formats check here

Saving Figures

Save our nice figure to a png file using savefig()


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

#Prepare some data
x = np.random.normal(0,1.0/3.0,1000)
y = np.random.normal(0,1.0/3.0,1000)
heatmap, xedges, yedges = np.histogram2d(-y, x, bins=[20, 20])
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

#Generate a figure with two axes, next to each other
fig = plt.figure(figsize=(9, 4), dpi=100)  # Size in inches
axLeft = fig.add_subplot(121)
axRight = fig.add_subplot(122)

#Plot scattering plot left
axLeft.set_title('Scatter plot')
axLeft.scatter(x, y)
axLeft.set_xlim(xedges[0], xedges[-1])
axLeft.set_ylim(yedges[0], yedges[-1])

#Plot histogram right
axRight.imshow(heatmap, extent=extent, interpolation='none')
axRight.set_title('Histogram plot')
axRight.set_axis_off()
axRight.set_xlim(xedges[0], xedges[-1])
axRight.set_ylim(yedges[0], yedges[-1])

#Add some annotations
axLeft.annotate('The Center(0, 0)', xy=(0.0, 0.0),  xycoords='data',
                    xytext=(-300, 30), textcoords='offset points', color='y', fontsize=18,
                    arrowprops=dict(arrowstyle="->", color='y'))                           
                                                                                
axRight.annotate('The Center\n(0, 0)', xy=(0, 0),  xycoords='data',          
                 xytext=(200, 30), textcoords='offset points', color='#CF21CC', fontsize=18,
                 arrowprops=dict(arrowstyle="fancy", color='#CF21CC', linewidth=1))
                                                                                                                                                               
fig.text(0.5, 0.3, 'Hello Bob', color='r', fontsize=20, rotation='vertical')    

#Show results
plt.show()

#Save figure to a file
fig.savefig('./example_figure.png', dpi=100, bbox_inches='tight')



In [112]:
from IPython.display import Image
img = Image('./example_figure.png')
img


Out[112]:

Moving and aranging figure elements


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

#Prepare some data
x = np.random.normal(0,1.0/3.0,1000)
y = np.random.normal(0,1.0/3.0,1000)
heatmap, xedges, yedges = np.histogram2d(-y, x, bins=[20, 20])
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

#Generate a figure with two axes, next to each other
fig = plt.figure(figsize=(9, 4), dpi=100)  # Size in inches (width, heigh)
axLeft = fig.add_subplot(121)
axRight = fig.add_subplot(122)

#Adjust figure positions
fig.subplots_adjust(top=0.0, bottom=0.0, wspace=0.3)

#Plot scattering plot left
axLeft.set_title('Scatter plot')
axLeft.scatter(x, y)
axLeft.set_xlim(xedges[0], xedges[-1])
axLeft.set_ylim(yedges[0], yedges[-1])

#Plot histogram right
axRight.imshow(heatmap, extent=extent, interpolation='none')
axRight.set_title('Histogram plot')
axRight.set_axis_off()
axRight.set_xlim(xedges[0], xedges[-1])
axRight.set_ylim(yedges[0], yedges[-1])

#Add some annotations
axLeft.annotate('The Center(0, 0)', xy=(0.0, 0.0),  xycoords='data',
                    xytext=(-300, 30), textcoords='offset points', color='y', fontsize=18,
                    arrowprops=dict(arrowstyle="->", color='y'))                           
                                                                                
axRight.annotate('The Center\n(0, 0)', xy=(0, 0),  xycoords='data',          
                 xytext=(200, 30), textcoords='offset points', color='#CF21CC', fontsize=18,
                 arrowprops=dict(arrowstyle="fancy", color='#CF21CC', linewidth=1))
                                                                                                                                                               
fig.text(0.5, 0.3, 'Hello Bob', color='r', fontsize=20, rotation='vertical')    

#Show results
plt.show()


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-176-50e06ee63bfe> in <module>()
     14 
     15 #Adjust figure positions
---> 16 fig.subplots_adjust(top=0.0, bottom=0.0, wspace=0.3)
     17 
     18 #Plot scattering plot left

/work/projects/vEnv/lib/python3.4/site-packages/matplotlib/figure.py in subplots_adjust(self, *args, **kwargs)
   1466 
   1467         """
-> 1468         self.subplotpars.update(*args, **kwargs)
   1469         for ax in self.axes:
   1470             if not isinstance(ax, SubplotBase):

/work/projects/vEnv/lib/python3.4/site-packages/matplotlib/figure.py in update(self, left, bottom, right, top, wspace, hspace)
    220             if self.bottom >= self.top:
    221                 reset()
--> 222                 raise ValueError('bottom cannot be >= top')
    223 
    224     def _update_this(self, s, val):

ValueError: bottom cannot be >= top

Chaning Image Ratios


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

#Prepare some data
x = np.random.normal(0,1.0/3.0,1000)
y = np.random.normal(0,1.0/3.0,1000)
heatmap, xedges, yedges = np.histogram2d(-y, x, bins=[20, 20])
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

#Generate a figure with two axes, next to each other
fig = plt.figure(figsize=(10, 4))  # Size in inches
ax1 = fig.add_subplot(131)
ax2 = fig.add_subplot(132)
ax3 = fig.add_subplot(133)


#Take aspect ratio from rc config file
ax1.set_title('Ratio None')
ax1.imshow(heatmap, extent=extent, interpolation='none', aspect=None)

#Fill the whole subfigure area
ax2.set_title('Ratio auto')
ax2.imshow(heatmap, extent=extent, interpolation='none', aspect='auto')

#Use the set ratio
ax3.set_title('Ratio 1.0/3.0')
ax3.imshow(heatmap, extent=extent, interpolation='none', aspect=1.0/3.0)


#Show results
plt.show()