Sunteți pe pagina 1din 35

Plotting with Matlab

x = 0:pi/30:2*pi; % x vector, 0 <= x <= 2*pi, increments of pi/30 y = sin(3*x); % vector of y values plot(x,y) % create the plot xlabel('x (radians)'); % label the x-axis ylabel('sine function'); % label the y-axis > title('sin(3*x)'); % put a title on the plot

Symbol plot
plot(x,y,'o'); plot(x,y,'r:');

Symbol plot
x = 0:0.01:2; % generate the x-vector noise = 0.02*randn(size(x)); % and noise y = 5*x.*exp(-3*x) + noise; % Add noise to known function plot(x,y,'o'); % and plot with symbols xlabel('x (arbitrary units)'); % add axis labels and plot title ylabel('y (arbitrary units)'); title('Plot of y = 5*x*exp(-3*x) + noise');

Multiple plots
The legend is used to label the different data curves when more than one curve is drawn on the same plot. The syntax is legend('label1','label2',...) The plot command will put multiple curves on the same plot with the following syntax plot(x1,y1,s1,x2,y2,s2,x3,y3,s3,...)

Plot from file


load PDXprecip.dat; % read data into PDXprecip matrix month = PDXprecip(:,1); % copy first column of PDXprecip into month precip = PDXprecip(:,2); % and second column into precip plot(month,precip,'o'); % plot precip vs. month with circles xlabel('month of the year'); % add axis labels and plot title ylabel('mean precipitation (inches)'); title('Mean monthly precipitation at Portland International Airport');

Multiple plots in the same window


Hold on By default, MATLAB finds the maxima and minima of the data and chooses the axis limits to span this range. The axis command enables you to specify your own limits: axis([xmin xmax ymin ymax]) Grid -Setting Grid Lines

Adding text
text(1,-1/3,'{\itNote the odd symmetry.}') Disp(text)

Programmatic Plotting
Prepare your data Select a window and position a plot region within the window Call elementary plotting function Select line and marker characteristics set(h,'LineWidth',2,{'LineStyle'}, {'--';':';'-.'}) set(h,{'Color'},{'r';'g';'b'}) Set axis limits, tick marks, and grid lines Annotate the graph with axis labels, legend, and text Export graph

t = 0:pi/100:2*pi; y = sin(t); plot(t,y) grid on % Turn on grid lines for this plot

y = sin(t); y2 = sin(t-0.25); y3 = sin(t-0.5); plot(t,y,t,y2,t,y3)

Different linestyles
t = 0:pi/100:2*pi; y = sin(t); y2 = sin(t-0.25); y3 = sin(t-0.5); plot(t,y,'-',t,y2,'--',t,y3,':')

Colors, Line Styles, and Markers


The basic plotting functions accepts character-string arguments that specify various line styles, marker symbols, and colors for each vector plotted. In the general form, plot(x,y,'linestyle_marker_color') linestyle_marker_color is a character string (delineated by single quotation marks) constructed from A line style (e.g., dashed, dotted, etc.) A marker type (e.g., x, *, o, etc.) A predefined color specifier (c, m, y, k, r, g, b, w) plot(x,y,':squarey') plots a yellow dotted line and places square markers at each data point. If you specify a marker type, but not a line style, only the marker is plotted. The specification can consist of one or none of each specifier in any order. For example, the string 'go--' defines a dashed line with circular markers, both colored green

Graphics handlers
x = 1:10; y = x.^3; h = plot(x,y); You can use the handle h to set the properties of the lineseries object. For example, you can set its Color property set(h,'Color','red') get(h,'LineWidth')

Graphical user interface


guide

Supported Image Formats


MATLAB supports the following graphics file formats, along with others: BMP (Microsoft Windows Bitmap) GIF (Graphics Interchange Files) HDF (Hierarchical Data Format) JPEG (Joint Photographic Experts Group) PCX (Paintbrush) PNG (Portable Network Graphics) TIFF (Tagged Image File Format) XWD (X Window Dump)

MATLAB math supports three different numeric classes for image display: double-precision floating-point (double) 16-bit unsigned integer (uint16) 8-bit unsigned integer (uint8)

Image functions and utlities


Image image (create image object). imagescScale data and display as image. imreadRead image from graphics file.File I/O imwriteWrite image to graphics file.File I/O imfinfoGet image information from graphics file.Utility ind2rgbConvert indexed image to RGB image.Utility

Image Types
Indexed Images Intensity Images RGB (Truecolor) Images

Image loading
Load or save a matrix as a MAT-file. load Save Load or save graphics file format image, e.g., BMP, TIFF. Imread Imwrite Display any image loaded into the MATLAB workspace. Image Imagesc Utilities imfinfo ind2rgb

load mandrill figure('color','k') image(X) colormap(map) axis off % Remove axis ticks and numbers axis image % Set aspect ratio to obtain square pixels

Figure ax(1) = subplot(1,2,1); rgb = imread('ngc6543a.jpg'); image(rgb); title('RGB image') ax(2) = subplot(122); im = mean(rgb,3); image(im); title('Intensity Heat Map') colormap(hot(256)) linkaxes(ax,'xy') axis(ax,'image')

Coloring Techniques
You can enhance the information content of surface plots by controlling the way MATLAB graphics apply color to these plots. MATLAB can map particular data values to colors specified explicitly or can map the entire range of data to a predefined range of colors called a colormap.

three different coloring techniques


Indexed Color Surfaces Direct and Scaled Color Mapping MATLAB colors the surface plot by assigning each data point an index into the figure's colormap. The way MATLAB applies these colors depends on the type of shading used (faceted, flat, or interpolated). Truecolor Surfaces MATLAB colors the surface plot using the explicitly specified colors (i.e., the RGB triplets). The way MATLAB applies these colors depends on the type of shading used (faceted, flat, or interpolated). To be rendered accurately, truecolor requires computers with 24-bit displays; however, MATLAB simulates truecolor on indexed systems. See the shading command for information on the types of shading.(OpenGL method) Texture Mapping Texture mapping displays a 2-D image mapped onto a 3-D surface.

Color maps
Each MATLAB figure window has a colormap associated with it. A colormap is simply a three-column matrix whose length is equal to the number of colors it defines. Each row of the matrix defines a particular color by specifying three values in the range zero to one. These values define the RGB components (i.e., the intensities of the red, green, and blue video components).

The colormap function, with no arguments, returns the current figure's colormap. For example, the MATLAB default colormap contains 64 colors and the 57th color is red. cm = colormap; cm(57,:) ans = 1 0 0

RGB Color Components


Red Green Blue Color

0 1 1 0 0 1 1 0 0.5 0.5 1 0.49

0 1 0 1 0 1 0 1 0.5 0 0.62 1

0 1 0 0 1 0 1 1 0.5 0 0.40 0.83

Black White Red Green Blue Yellow Magenta Cyan Gray Dark red Copper Aquamarine

You can create colormaps with MATLAB array operations or you can use any of several functions that generate useful maps, including hsv, hot, cool, summer, and gray. Each function has an optional parameter that specifies the number of rows in the resulting map.

Displaying Colormaps
The colorbar function displays the current colormap, either vertically or horizontally, in the figure window along with your graph. For example, the statements [x,y] = meshgrid([-2:.2:2]); Z = x.*exp(-x.^2-y.^2); surf(x,y,Z,gradient(Z)) colorbar produce a surface plot and a vertical strip of color corresponding to the colormap. The colorbar indicates the mapping of data value to color with the axis labels.

Total graphics
Prepare your data. Z = peaks(20); Select window and position plot region within window. figure(1);subplot(2,1,2) Call 3-D graphing function. h = surf(Z); Set colormap and shading algorithm. colormap hot shading interp set(h,'EdgeColor','k') Add lighting. light('Position',[-2,2,20]) lighting phong material([0.4,0.6,0.5,30]) set(h,'FaceColor',[0.7 0.7 0],... 'BackFaceLighting','lit') Set viewpoint view([30,25]) set(gca,'CameraViewAngleMode','Manual')

Set axis limits and tick marks. axis([5 15 5 15 -8 8]) set(gca,'ZTickLabel','Negative||Positive') Set aspect ratio. set(gca,'PlotBoxAspectRatio',[2.5 2.5 1]) Annotate the graph with axis labels, legend, and text. xlabel('X Axis') ylabel('Y Axis') zlabel('Function Value') title('Peaks') Print graph. set(gcf,'PaperPositionMode','auto') print -dps2

3D plot
t = 0:pi/50:10*pi; plot3(sin(t),cos(t),t) axis square; grid on

Plotting matrix data


[X,Y] = meshgrid([-2:0.1:2]); Z = X.*exp(-X.^2-Y.^2); plot3(X,Y,Z) grid on

Visualizing Functions of Two Variables


To display a function of two variables, z = f(x,y), generate X and Y matrices consisting of repeated rows and columns, respectively, over the domain of the function. You will use these matrices to evaluate and graph the function. The meshgrid function transforms the domain specified by two vectors, x and y, into matrices X and Y. You then use these matrices to evaluate functions of two variables: The rows of X are copies of the vector x and the columns of Y are copies of the vector y.

The rest
Lighting control Object transparency Visualizing volume functions

S-ar putea să vă placă și