PlotBasics: Difference between revisions

From CASA Guides
Jump to navigationJump to search
Line 12: Line 12:


=== Supernova Cosmology Example ===
=== Supernova Cosmology Example ===
#  We will import the pyplot and numpy packages
<source lang="Python">
import numpy as np
import matplotlib.pyplot as plt
</source>
We are going to download data from the internet so
<source lang="Python">
import urllib
</source>
Begin by reading the Union2 SN cosmology data from LBL, because
they are fun. 
<source lang="Python">
# initialize arrays and read in data from the web
# list of names
SN_list = ['']
z_array = np.array([])
mod_array = np.array([])
moderr_array = np.array([])
f = urllib.urlopen('http://supernova.lbl.gov/Union/figures/SCPUnion2_mu_vs_z.txt')
for line in f:
    if line[0] == '#': continue    # Ignore anything that starts with a #
    SN, z, mod, moderr = line.split()
    SN_list.append(SN)
    z_array = np.append(z_array,np.float64(z))
    mod_array = np.append(mod_array,np.float64(mod))
    moderr_array = np.append(moderr_array,np.float64(moderr)) 
f.close()
<\source>
# First we close whatever windows we might have:
plt.close()
# Now let us plot some points
plt.plot(z_array, mod_array)
# Notice it is a mess, by default it connects the lines
# We close the window with plt.close()
temp=raw_input("hit enter to show next plot")
plt.close()
# We clearly need axes lables
plt.xlabel('z', fontsize=20)
# But we want a Greek Letter, so we can put some LaTeX syle code with the r command:
plt.ylabel(r'$\mu=m-M$', fontsize=20)
plt.title("Union2 SN Cosmology Data")
# Now we add a format string, as follows:
plt.plot(z_array, mod_array,'ro')
#  Now this looks better, we have red circles
temp=raw_input("hit enter to show next plot")
plt.close()
# Now let's plot with the error bars
plt.errorbar(z_array, mod_array, yerr=moderr_array, fmt='.')
# And putting lables and colors we can do:
plt.xlabel(r'$z$', fontsize=20)
plt.ylabel(r'$\mu=m-M$', fontsize=20)
plt.title("Union2 SN Cosmology Data")
plt.errorbar(z_array, mod_array, yerr=moderr_array, fmt='.', capsize=0,
    elinewidth=1.0, ecolor=(0.6,0.0,1.0), color='green' )
#  Notice that colors can be specified in the format commond, on in a color command.
#  They can be given via an RGB tuple, a name, or a single number between 0 and 1 for
#  gray scale.
#  Now we can save it as a pdf, or most other formats, with:
#plt.savefig('Union2_plot1.pdf', format="pdf", transparent=True, bbox_inches='tight')
temp=raw_input("hit enter to show next plot")
plt.close()
# Now there are a lot of points, so let's figure our what our distribution is in z
plt.hist(z_array, 25)
# And slap a label on it
plt.xlabel(r'$z$', fontsize=20)
temp=raw_input("hit enter to show next plot")
plt.close()
# Now, let's find the real distance from the distance modulus.
# To do this we will define a function and a constant
def distance_Mly(m,z):
    return 0.0000326 * (10**(m/5)) / (1.0 + z)
c = 299792.458    # km/s
#Now:
d_array = distance_Mly(mod_array,z_array)
# Now we will calculate the error bars in the distance, both ways:
d_error_plus = distance_Mly((mod_array+moderr_array),z_array) - d_array
d_error_minus = d_array - distance_Mly((mod_array-moderr_array),z_array)
# And plot the graph with asymetrical horizontal error bars, and lables
# Notice the different color formats that can be used.
plt.errorbar(d_array, c*z_array, xerr=(d_error_minus,d_error_plus), fmt='s',
    capsize=5, elinewidth=1.0, color=(0.4,0.0,1.0), ecolor='aqua', barsabove=True)
plt.ylabel('cz (km/s)', fontsize=15, color='0.0')
plt.xlabel('Distance (Mly)', fontsize=10, color='g')
plt.title("Union2 SN Cosmology Data", color=(0.4,0.0,1.0))
temp=raw_input("hit enter to show next plot")
plt.close()
# Now we will plot with a second vertical and horizontal axis
plt.errorbar(d_array/1000.0, c*z_array, xerr=(d_error_minus/1000.0,d_error_plus/1000.0), fmt='.',
    capsize=0, elinewidth=1.0, color=(0.4,0.0,1.0), ecolor='aqua', barsabove=True)
# Now we make room for each axis
plt.subplots_adjust(right=0.875, top=0.8)
plt.ylabel('cz (km/s)', fontsize=15, color='aqua')
plt.xlabel('Distance (Gly)', fontsize=15, color='aqua')
axes1_range = np.array( plt.axis() )  # get the default axes and convert to n array
print(axes1_range)
axes2_range = 1.0*axes1_range  # Don't forget, we need to make it copy it.
axes2_range[0:2] = 1000*axes1_range[0:2]/3.26  # set second y-axis to z 
axes2_range[2:4] = axes1_range[2:4]/c # set second y-axis to z 
print(axes2_range)
#now we switch to the second axis
temp=raw_input("hit enter to show next plot")
plt.twinx()  #  This swaps the Y axis
plt.ylabel('z', fontsize=15, color='r')  #  I am not sure why this has to be before plt.twiny()
plt.twiny()  #  This swaps the X axis
plt.xlabel('Distance (Mpc)', fontsize=15, color='purple')
plt.axis(axes2_range, axisbg='#d0,1f,ff')
plt.title("Union2 SN Cosmology Data", color=(0.4,0.0,1.0), x=0.5, y=1.15)

Revision as of 14:34, 31 October 2011

3 Ways to plot

There are three ways to go about plotting in matplotlib.

1. You can use the pylab environment

2. You can use the matplotlib.pyplot environment, with plotting commands and functions.

3. You can define plot objects, and then use the pyplot methods on those objects.

The last way gives you most control, but the other two are somewhat easier. We will give examples using the last two ways here.

Supernova Cosmology Example

  1. We will import the pyplot and numpy packages
import numpy as np
import matplotlib.pyplot as plt


We are going to download data from the internet so

import urllib

Begin by reading the Union2 SN cosmology data from LBL, because they are fun. <source lang="Python">

  1. initialize arrays and read in data from the web
  2. list of names

SN_list = [] z_array = np.array([]) mod_array = np.array([]) moderr_array = np.array([]) f = urllib.urlopen('http://supernova.lbl.gov/Union/figures/SCPUnion2_mu_vs_z.txt') for line in f:

   if line[0] == '#': continue    # Ignore anything that starts with a #
   SN, z, mod, moderr = line.split()
   SN_list.append(SN)
   z_array = np.append(z_array,np.float64(z))
   mod_array = np.append(mod_array,np.float64(mod))
   moderr_array = np.append(moderr_array,np.float64(moderr))   

f.close() <\source>


  1. First we close whatever windows we might have:

plt.close()

  1. Now let us plot some points

plt.plot(z_array, mod_array)

  1. Notice it is a mess, by default it connects the lines
  2. We close the window with plt.close()

temp=raw_input("hit enter to show next plot") plt.close()

  1. We clearly need axes lables

plt.xlabel('z', fontsize=20)

  1. But we want a Greek Letter, so we can put some LaTeX syle code with the r command:

plt.ylabel(r'$\mu=m-M$', fontsize=20) plt.title("Union2 SN Cosmology Data")

  1. Now we add a format string, as follows:

plt.plot(z_array, mod_array,'ro')

  1. Now this looks better, we have red circles

temp=raw_input("hit enter to show next plot") plt.close()


  1. Now let's plot with the error bars

plt.errorbar(z_array, mod_array, yerr=moderr_array, fmt='.')

  1. And putting lables and colors we can do:

plt.xlabel(r'$z$', fontsize=20) plt.ylabel(r'$\mu=m-M$', fontsize=20) plt.title("Union2 SN Cosmology Data") plt.errorbar(z_array, mod_array, yerr=moderr_array, fmt='.', capsize=0,

   elinewidth=1.0, ecolor=(0.6,0.0,1.0), color='green' )
  1. Notice that colors can be specified in the format commond, on in a color command.
  2. They can be given via an RGB tuple, a name, or a single number between 0 and 1 for
  3. gray scale.
  1. Now we can save it as a pdf, or most other formats, with:
  2. plt.savefig('Union2_plot1.pdf', format="pdf", transparent=True, bbox_inches='tight')

temp=raw_input("hit enter to show next plot") plt.close()

  1. Now there are a lot of points, so let's figure our what our distribution is in z

plt.hist(z_array, 25)

  1. And slap a label on it

plt.xlabel(r'$z$', fontsize=20)

temp=raw_input("hit enter to show next plot") plt.close()

  1. Now, let's find the real distance from the distance modulus.
  2. To do this we will define a function and a constant

def distance_Mly(m,z):

   return 0.0000326 * (10**(m/5)) / (1.0 + z)

c = 299792.458 # km/s

  1. Now:

d_array = distance_Mly(mod_array,z_array)

  1. Now we will calculate the error bars in the distance, both ways:

d_error_plus = distance_Mly((mod_array+moderr_array),z_array) - d_array d_error_minus = d_array - distance_Mly((mod_array-moderr_array),z_array)

  1. And plot the graph with asymetrical horizontal error bars, and lables
  2. Notice the different color formats that can be used.

plt.errorbar(d_array, c*z_array, xerr=(d_error_minus,d_error_plus), fmt='s',

   capsize=5, elinewidth=1.0, color=(0.4,0.0,1.0), ecolor='aqua', barsabove=True)

plt.ylabel('cz (km/s)', fontsize=15, color='0.0') plt.xlabel('Distance (Mly)', fontsize=10, color='g') plt.title("Union2 SN Cosmology Data", color=(0.4,0.0,1.0))

temp=raw_input("hit enter to show next plot") plt.close()

  1. Now we will plot with a second vertical and horizontal axis

plt.errorbar(d_array/1000.0, c*z_array, xerr=(d_error_minus/1000.0,d_error_plus/1000.0), fmt='.',

   capsize=0, elinewidth=1.0, color=(0.4,0.0,1.0), ecolor='aqua', barsabove=True)
  1. Now we make room for each axis

plt.subplots_adjust(right=0.875, top=0.8)

plt.ylabel('cz (km/s)', fontsize=15, color='aqua') plt.xlabel('Distance (Gly)', fontsize=15, color='aqua') axes1_range = np.array( plt.axis() ) # get the default axes and convert to n array print(axes1_range)

axes2_range = 1.0*axes1_range # Don't forget, we need to make it copy it. axes2_range[0:2] = 1000*axes1_range[0:2]/3.26 # set second y-axis to z axes2_range[2:4] = axes1_range[2:4]/c # set second y-axis to z print(axes2_range)

  1. now we switch to the second axis

temp=raw_input("hit enter to show next plot") plt.twinx() # This swaps the Y axis plt.ylabel('z', fontsize=15, color='r') # I am not sure why this has to be before plt.twiny() plt.twiny() # This swaps the X axis plt.xlabel('Distance (Mpc)', fontsize=15, color='purple') plt.axis(axes2_range, axisbg='#d0,1f,ff') plt.title("Union2 SN Cosmology Data", color=(0.4,0.0,1.0), x=0.5, y=1.15)