PyPlot. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as

Similar documents
PyPlot. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving MATLAB Tutorial Vb

Classes 7-8 (4 hours). Graphics in Matlab.

Overview. Lecture 13: Graphics and Visualisation. Graphics & Visualisation 2D plotting. Graphics and visualisation of data in Matlab

Introductory Scientific Computing with Python

Logical Subscripting: This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression.

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006

Introduction to MATLAB

Dr Richard Greenaway

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

This module aims to introduce Precalculus high school students to the basic capabilities of Matlab by using functions. Matlab will be used in

MATLAB Introduction to MATLAB Programming

Basic Beginners Introduction to plotting in Python

Python Crash Course Numpy, Scipy, Matplotlib

Matlab Tutorial 1: Working with variables, arrays, and plotting

Graphics Example a final product:

PART 1 PROGRAMMING WITH MATHLAB

The Department of Engineering Science The University of Auckland Welcome to ENGGEN 131 Engineering Computation and Software Development

Introduction to MATLAB: Graphics

Basic Graphs. Dmitry Adamskiy 16 November 2011

Using the Matplotlib Library in Python 3

Prof. Manoochehr Shirzaei. RaTlab.asu.edu

Chapter 2 Scatter Plots and Introduction to Graphing

Mechanical Engineering Department Second Year (2015)

Lab 4: Structured Programming I

1 Introduction to Matlab

Bi 1x Spring 2014: Plotting and linear regression

INTRODUCTION TO MATLAB PLOTTING WITH MATLAB

Scientific Python: matplotlib

fplot Syntax Description Examples Plot Symbolic Expression Plot symbolic expression or function fplot(f) fplot(f,[xmin xmax])

Chapter 3: Introduction to MATLAB Programming (4 th ed.)

Years after US Student to Teacher Ratio

Creating a Basic Chart in Excel 2007

Dr. Iyad Jafar. Adapted from the publisher slides

Introduction to MATLAB

Graphics in MATLAB. Responsible teacher: Anatoliy Malyarenko. November 10, Abstract. Basic Plotting Commands

Plotting With matplotlib

X-values are restricted to [Xmin,Xmax].

Excel Core Certification

Visualisation in python (with Matplotlib)

Computational Foundations of Cognitive Science. Inverse. Inverse. Inverse Determinant

Basic plotting commands Types of plots Customizing plots graphically Specifying color Customizing plots programmatically Exporting figures

Chapter 2 (Part 2) MATLAB Basics. dr.dcd.h CS 101 /SJC 5th Edition 1

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

INC151 Electrical Engineering Software Practice. MATLAB Graphics. Dr.Wanchak Lenwari :Control System and Instrumentation Engineering, KMUTT 1

TikZ & PGF(plots) Daniel Knittl-Frank. May This work is licensed under the Creative Commons Attribution-ShareAlike 3.

Models for Nurses: Quadratic Model ( ) Linear Model Dx ( ) x Models for Doctors:

Chapter 1 Histograms, Scatterplots, and Graphs of Functions

Graphics and plotting techniques

PROGRAMMING WITH MATLAB WEEK 6

Introduction to MATLAB Programming. Chapter 3. Linguaggio Programmazione Matlab-Simulink (2017/2018)

W1005 Intro to CS and Programming in MATLAB. Plo9ng & Visualiza?on. Fall 2014 Instructor: Ilia Vovsha. hgp://

2D LINE PLOTS... 1 The plot() Command... 1 Labeling and Annotating Figures... 5 The subplot() Command... 7 The polarplot() Command...

Getting Started with DADiSP

Code_Aster. Operator IMPR_FONCTION. 1 Goal

Math 227 EXCEL / MEGASTAT Guide

Chapter 2. MATLAB Fundamentals

QUICK INTRODUCTION TO MATLAB PART I

Working with Charts Stratum.Viewer 6

Introduction to Matlab

MATLAB for Image Processing. April 2018 Rod Dockter

Quadratics Functions: Review

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University

is the data file to be processed. Note that Path/InputFilename is NOT preceded by a "<" on the command line.

APPM 2460 PLOTTING IN MATLAB

Additional Plot Types and Plot Formatting

Time series plots and phase plane plots Graphics

DATA PLOTTING WITH MATLAB

CHAOS Chaos Chaos Iterate

Total Number of Students in US (millions)

Code_Aster. Operator IMPR_FONCTION. 1 Drank

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

Chemistry Excel. Microsoft 2007

MATLAB SUMMARY FOR MATH2070/2970

Lesson 4 Customize the ToolBox

Points Lines Connected points X-Y Scatter. X-Y Matrix Star Plot Histogram Box Plot. Bar Group Bar Stacked H-Bar Grouped H-Bar Stacked

MATLAB for Image Processing

The 3 Voxet axes can be annotated: Menu > Voxet > Tools > Annotate Voxet > Custom system.

GRAPHICS AND VISUALISATION WITH MATLAB

DataPlotClasses for REALBasic

Math Sciences Computing Center. University ofwashington. September, Fundamentals Making Plots Printing and Saving Graphs...

Organizing and Summarizing Data

CSC 1315! Data Science

ArcView QuickStart Guide. Contents. The ArcView Screen. Elements of an ArcView Project. Creating an ArcView Project. Adding Themes to Views

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University

Activity: page 1/10 Introduction to Excel. Getting Started

STIPlotDigitizer. User s Manual

Getting Started. Chapter 1. How to Get Matlab. 1.1 Before We Begin Matlab to Accompany Lay s Linear Algebra Text

Foundations of Math II

Polygons in the Coordinate Plane

Desktop Studio: Charts. Version: 7.3

Dealing with Data in Excel 2013/2016

Computer Programming in MATLAB

Introduction to MATLAB

The Mathcad Workspace 7

EE168 Lab/Homework #1 Introduction to Digital Image Processing Handout #3

MATLAB INTRODUCTION. Matlab can be used interactively as a super hand calculator, or, more powerfully, run using scripts (i.e., programs).

Charts in Excel 2003

Lecture #3. MATLAB image processing (cont.) Histograms Mathematics of image processing Geometric transforms Image Warping.

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 8 Plots and Graphs

Transcription:

Geog 271 Geographic Data Analysis Fall 2015 PyPlot Graphicscanbeproducedin Pythonviaavarietyofpackages. We willuseapythonplotting package that is part of MatPlotLib, for which documentation can be found at matplotlib.org. This handout covers a very small subset of the graphics methods available and provides only a brief description of each one, so use of the documentation web site will be necessary. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as enabling simplified calls like import pl.plot(x,y) The plotting routines can be grouped in three different categories. The main set does most of the design and plotting: plot, hist, contour, and scatter are general types of graph. Another group adds labels, axes, and related annotation, such as title and xlabel.the third set starts, completes, and saves graphics, including show, figure, and savefig. plot and scatter The plot function produces connected curve plots or scatter plots, with the capability of combining them. The most basic call is plot( x, y ) in which x and y are one-dimensional, floating-point arrays of coordinates to be connected with a curve. To produce a scatter plot, add a format argument. plot( x, y, ro ) in which ro causes the points to be plotted individually with red circles. The color abbreviations and marker or line designators used in formats are in tables at the end of this handout. More than one curve or marker set can be plotted on a graph. plot( x, y, y--, u, v, b* ) in which x and y must be of the same size and will be plotted with a dashed-yellow curve, and u and v must be the same size as each other but not necessarily the same size as the (x,y) set, and the (u,v) set will be plotted with blue stars. To have those curves and scatter plots labeled within a figure, use two different plot calls and the label keyword argument which provides information for a later call to legend. plot( x, y, y--, label= smoothed curve ) plot( u, v, b*, label= raw data ) The scatter function is more limited and only puts markers at a set of points. A good use for it is to mark the raw data locations under a contour plot. scatter( x, y, marker= o, c= r ) will plot a red circle at each (x,y) location.

2 contour and imshow hist The hist function creates a histogram a form of bar chart that reduces a list of numbers to the frequency of their occurrence in bins, which are defined as short subranges of the data, defined by values at the boundaries between ranges. In the simplest form, it only needs a list of numbers. hist( x ) will determine the range of values in x (highest and lowest values, break that range into 10 evenly spaced bins, count the number of values in each bin, and plot the resulting frequencies. Arguments can be used to change the default behavior in a variety of ways. hist( x, bins=nbins ) where nbins is an integer number that controlshow many bins are used instead of the default 10. hist( x, bins=list of bins ) wherelist of binsis asequenceofnumbersthat become the actualbin edges, allowinguneven bins to be specified. hist( x, cumulative=1 ) changes the histogram values from regular frequencies into cumulative frequencies in which the value of each histogram bar is the number of points less than or equal to the right-edge value of the bin. Setting cumulative=-1 produces a reverse cumulative chart in which each bar is the number of points greater than or equal to the left-edge value. hist( x, range=[x min,x max] ) restricts the range of the x axis, so that data outside that range will be ignored. contour and imshow The contour and contourf functions produces contour plots, as might be expected, with contourf doing color fill between contours whereas contour just draws the curves. Turning a set of data into a contour plot often requires an intermediate step. Looking at the online Gallery for example codes may be particularly helpful in this case. Contouring routines normally require a two-dimensional array of values arrayed in a grid. If the grid is defined by a set of evenly spaced x values and evenly spaced y values, then a z array in two dimensions that contains all the possible pairs of x and y coordinates can be contoured as simply as contour( x, y, z ) If the x and y values do not actually matter, this can be simplified to contour( z ) in which case the x and y coordinates will assume each grid point has a spacing of 1 (i.e., the axes will count position numbers on the grid).

contour and imshow 3 The more typical case of having randomly located data requires that a grid be created first, which can be accomplished with the griddata function from the mlab library. Also, the default contour call does not label the contour lines, which requires interface with the clabel function. Both of these concepts are better learned by examining the source code examples in the PyPlot gallery, rather than by a brief description here. However, the following example takes three one-dimensional arrays of the same size, x, y, and z, creates evenly spaced xg and yg grid definitions by dividing the range of those two variables into 20 equal segments, uses the griddata function (which must be imported from another sublibrary) to create a two-dimensional zg array with interpolated values of z at all the possible combinations of xg and yg, and then plots a contour diagram of the resulting grid. import matplotlib.mlab as mlab. xmin = min(x); xmax=max(x); xinc=(xmax - xmin)/20.0 ymin = min(y); ymax=max(y); yinc=(ymax - ymin)/20.0 xg = np.arange(xmin, xmax, xinc ) yg = np.arange(ymin, ymax, yinc ) zg = mlab.griddata(x, y, z, xg, yg, interp= linear ) pl.contour(xg, yg, zg) The imshow function also requires as input a two-dimensional array, such as z in the contouring examples. Instead of doing contour lines, imshow produces a color map. Thus, imshow( z ) would produce a color map of z as a third dimension over the two-dimensional space defined by its index positions. One means of creating a two-dimensional array is to read an image file, in which the color or intensity values of the array become the z values. This requires importing an additional library. In the following example, raster.png is assumed to be an existing image file, PNG format implied by the filetype. The file will be read by the image function from the matplotlib.image library. import matplotlib.image as img. a = img.imread("raster.png") pl.imshow( a ) The preceding calls only reproduce the image in raster.png as a PyPlot graph. However, they enable pixel by pixel image manipulation using Python arithmetic and programming on the values in the arraya. Figuring out exactly what to do with this is an advanced topic. The imread function recognizes the most commonly used image file formats, including png, tiff, jpeg, and gif.

4 Axes and Labels Both contour and imshow have additional arguments and graphics resources that can be used to control colors of contours, color maps of the image, axis range and labeling, and labeling. As usual, starting with examples in the online PyPlot gallery to emulate and modify is the best way to learn the options. Axes and Labels For annotation of axes and the top of the graph, use any or all of the following calls in the obvious manner xlabel( Label text for x axis ) ylabel( Label text for y axis ) title( Label text for top of graph ) For annotation of individual curves, use legend. With a blank argument list, legend(), a box will be plotted in the upper right with text from label arguments. If the plot statements do not have labels, the following is an example of constructing a legend and moving it from the default position. legend( ( smoothed curve, raw data ), loc= upper left ) Note the extra parentheses around the list of labels. See the online documentation for allowable locations and other options. Text strings can be added anywhere in a graph using the annotate function. The location of the text string (x,y) is in the graph-relative coordinate system, so use coordinates as if they were data point locations is possible. The first example just puts a character string defined as object s into the graph at position (x,y): annotate( s, xy=(x,y) ) Annotate can also be used to put string s at location (x2,y2) with an arrow pointing at location (x,y). This requires use of an arrowprops keyword, which is best learned by gallery examples. The axis function provides several different controls on axis appearance. Often, the default choices are good enough and axis is not needed. Here are some useful examples when the default is not adequate. axis([xmin, xmax, ymin, ymax]) Sets the minimum and maximum values for each axis, using a list of numbers. axis( off ) Turns off axis lines and labels. axis( equal ) Changes limits of the axes so that both coverthe same range, i.e., so that xmax - xmin equals ymax - ymin. Useful when two-dimensional shapes need to be preserved, as in mapping. Also see axis( scaled ) which changes the length of the axes in order to preserve two-dimensional shapes.

Colors, Linestyles, and Markers 5 axlimits = axis() The blank argument list turns axis into an inquiry function, in which axlimits is a list of the xmin, xmax, ymin, ymax being used. Control of one or the other axis limits without needing to specify all of them is possible with xlim and ylim, which have the arguments (xmin,xmax) and (ymin,ymax), respectively. These may be overridden by axis calls. Examples: xlim(xmin=0) sets the bottom limit of the x axis while leaving the y axis alone and living the upperlimit of the x axis automatic, while ylim(ymin=-10,ymax=20) sets both limits for the y axis but leaves the x axis to be set automatically. Completing and saving figures The show function tells Python to plot the graph defined by the above calls; usually it is the last call of the graphics program for a single plot. show() The figure function may not be necessary in our course. It starts a new figure, gives it a number, and optionally changes the size. It is more useful in programs that work on more than one figure at a time, especially for panel plots. To give a figure a number other than 1, such as whatever number is currently stored in k, for example, figure(k) The savefig function is called just before show to save a file to disk in some format. The main argument is to provide a filename, from which the file format will usually be deduced. The following three examples save a file in the current directory (where the Python program is running), in a subdirectory, and to the Desktop using an absolute path. The file formats will be png, pdf, and jpeg, respectively. savefig( figure1.png ) savefig( graphs/figure2.pdf ) savefig( /Users/students/Desktop/figure3.jpg ) Colors, Linestyles, and Markers colors b blue g green r red c cyan m magenta y yellow k black w white line styles - solid (default) -- dashed -. dash-dot : dotted

6 Colors, Linestyles, and Markers markers. point (default), pixel 0 circle s square v triangle down ^ triangle up < triangle left > triangle right p pentagon h hexagon d diamond + plus * star x X vertical line horizontal line