R language Basic drawing function and multi-graph multi-line _r language

Source: Internet
Author: User
Tags cos sin
Common statistical Drawing function Summary plot () hist () straight square diagram stem () boxplot () Box line diagram (Box chart) Coplot () co-map Qqnorm () normal QQ diagram Qqplot () Two overall QQ Figure 1. Common options for advanced low-level graphics functions

Overview of high and low level graphics functions advanced graphical functions can quickly and easily draw common types of graphics, but in some cases you may want to draw some graphics with special requirements. For example, you want the axes to be drawn according to your design, add another set of data on an existing diagram, add a line of text annotations to the diagram, draw a label for the data represented by multiple curves, and so on. Lower-level graphics functions allow you to add on the basis of an existing diagram.
Low-level graphics functions generally need to specify location information, where the coordinates refers to the so-called user coordinates, that is, the previous advanced graphics functions established by the coordinates of the coordinate system. The coordinates can be given in two vectors x and y, or by a two-column matrix. If an interactive drawing can interactively enter the coordinate position directly from the graph, use the locator () function described below.

The most common advanced function is the plot () function. Like what
-Plot (X,y) (where x,y is a vector) draws a scatter plot of two variables.
-With plot (z) (where z is a list that defines the x and Y variables, or a two-column matrix), the same purpose can be achieved.
If X is a time series object (the time series object is generated with the TS () function), plot (x) draws the time series graph.
-If x is a normal vector, draw a scatter chart of the value of X to its subscript.
-If x is a complex vector, the scatter plot of the imaginary part to the real part is drawn.
-If f is a factor, then plot (f) draws the bar graph of F (the number of levels per factor).
-If f is a factor and y is a numerical vector of the same length, then plot (f,y) plots the corresponding numerical box in Y for each factor F.
-If D is a numeric data box, then plot (d) maps each of the two variables (scatter chart, etc.) to D

Load ("F:/R/CL.") RData ")
plot (cl$sex)

Advanced drawing functions Common options

Common options for low-level drawing functions

Low-level graphics functions generally need to specify location information, where the coordinates refers to the so-called user coordinates, that is, the previous advanced graphics functions established by the coordinates of the coordinate system. The coordinates can be given in two vectors x and y, or by a two-column matrix. If an interactive drawing can interactively enter the coordinate position directly from the graph, use the locator () function described below.

Graphic parameter details graphic element type explanation PCH Specifies the symbol used to draw the scatter. The points drawn are often slightly above or below the specified coordinate position, and are only pch= "." There is no such problem. LTY=2 Specifies the line style used for drawing lines. The default value Lty=1 is a solid line. Starting from 2 is a variety of dotted lines. lwd=2 Specifies the line weight, measured in standard line weight. This parameter affects the line width of the data curve and the line width of the axis. COL=2 specifies colors that can be applied to plot points, lines, text, fill areas, and images. Color values can also be specified with color names such as "Red", "blue". font=2 the integer used to specify the font. General Font=1 is Roman, 2 is bold, 3 is italic, 4 is black italic. Font.axisfont.labfont.mainfont.sub is used to specify the font used for a coordinate scale, an axis label, a title, and a small caption. adj=-0.1 Specifies how the text is aligned relative to the given coordinates. Take 0 for left-aligned, 1 for right, and 0.5 for center. The value of this parameter actually represents the proportion of the text that appears to the left of the given coordinates, so the effect of the adj=-0.1 is that the text appears to the right of the given coordinate position and empty the distance equivalent to 10% of the length of the text. cex=1.5 specifies the character magnification. Axes and coordinate scales many advanced graphics have axes, and you can add axis () separately without an axis. function box () to draw the four-week border of the coordinate area. Axes include three parts: axes (with lty can control line style), tick marks, tick marks. They can be controlled using the following graphic parameters: Parameter Interpretation lab=c (5, 7, 12) The first number for the X axis want to draw a few tick marks, the second number is the Y axis want to draw a few tick marks, this two number is recommended; The third number is how many characters the width of the coordinate scale label is, including the decimal point, This number is too small to round the tick labels to the same value. Las=1 the direction of the coordinate tick labels. 0 means always parallel to the axis, 1 is always horizontal, and 2 is always perpendicular to the axis. The position of the parts of the Mgp=c (3,1,0) axis. The first element is the distance from the axis position to the axis label, in the height of the text line. The second element is the distance from the axis position to the coordinate scale label. The third element is the distance from the axis position to the actual drawn axis, usually 0. tck=0.01 the axis tick mark length, in units of the plot area, and the value is the proportions of the drawing area. When the TCK is less than 0.5, the tick marks on the x and Y axes are unified to the same length. Take 1 o'clock to draw the grid line. A negative time line is drawn outside the drawing area. Xaxs= "S" yaxs= "D" controls the x-axis and y-axis Huazhou methods. Value is "s" (ie standard) or "E"(i.e. extended), the data range is controlled between the minimum scale and the maximum scale. When "E" is taken, if a number of positions are close to the edge axis, the range will be slightly enlarged. This Huazhou way sometimes leaves too much space on one side of the shaft. A value of "I" (that is, internal) or "R" (this is the default) causes tick marks to fall within the range of data, while the "R" method leaves a smaller margin. This axis is locked when the value is set to "D", and subsequent graphics use exactly the same axes as it does, which is useful when you want to generate a series of comparable shapes. To unlock, you need to set this graphic parameter to a different value. More than one page map

One-page mfrow parameters or Mfcol parameters, such as:

Par (Mfrow=c (3,2))
Indicates that the same page has three rows, two columns and six graphs, and the order is filled by rows. Similarly,

Par (Mfcol=c (3,2))
The same pane structure is specified, but the order is filled by columns, that is, fill the first column with three first and then fill in the second column.

Par (Mfrow=c (1,1)).
There is no outer space by default. To specify the outer space size, either OMI or OMA parameters can be used. OMI parameter is in inches, the OMA parameter is in the line of line height, two parameters are four elements of the vector, respectively, given the bottom, left, top and right side of the empty size. Such as:
Par (Oma=c (2,0,3,0))

function Mtext is used to add text annotations outside of space. Its usage is
Mtext (text, side = 3, line = 0, outer = FALSE)

You can also use the MFG parameter to jump directly to a pane in a multiple-graph environment, such as
Par (Mfg=c (2,2,3,2))
Represents a direct jump to the second column in a multiple-graph environment of three rows and two columns. The last two MFG parameters represent the number of rows and columns in the multiple-diagram environment, and the first two represent the locations to jump to.

You can draw a pane directly from anywhere in the page without using a multiple-diagram environment, and the parameters are fig, such as:
Par (Fig=c (4,9,1,4)/10)
This parameter is a vector, given the pane of the left, right, bottom, top edge position, take the value of the total page ratio, such as the above example in the lower right of the page to open a pane mapping. Graphics Edge Space

A separate figure in S consists of the drawing area (the point, line, etc. of the drawing in the area) and the Benis surrounding the drawing area, which can include axis labels, axis tick labels, headings, subheadings, and so on, and the drawing area is generally surrounded by axes.
The size of the side space is controlled by Mai or Mar parameters, they are all four elements of the vector, respectively, the bottom, left, top, right side of the empty size, where Mai takes the unit is in inches, and the Mar unit is the height of the text line. For example:

Par (MAI=C (1, 0.5, 0.5, 0))
Par (Mar=c (4, 2, 2, 1))

These two graphics parameters are not independent and setting one will affect the other. s default graphical margins are often too large to have a large portion of the entire graphic when the graphics window is smaller.
Usually we can cancel the right space, and we can greatly reduce the top space without the caption. For example, the following example can produce very compact graphics:
Oldpar <-par (mar=c (2,2,1,0.2))
Plot (X,y)
When you draw multiple graphs on one page, the margin is halved automatically, but we often need to further reduce the edge space to make the multiple graphs meaningful. Interactive graphic functions

The function locator (n, type) stops to wait for the user to click in the figure, and then returns the coordinates of the mouse click position in the graph. Waiting to click with the middle mouse button click can choose to stop waiting, return immediately. Parameter n Specifies how many times to click and automatically stop, the default is 500 times; parameter type if used, you can specify the type of the painting point, the same as the type parameter in the plot () function, and draw points (line, vertical, etc.) at the point of the mouse click. The return value of locator () is a list with two variables (elements) x and Y, preserving the horizontal and vertical coordinates of the click Position, respectively.

For example, to find an empty place to mark a line of text in an already drawn graph, use the following procedure:

The adj parameter of the text () function uses a number to represent the text string relative to the given coordinates, ADJ=0 indicates that the given coordinates are the coordinates to the left of the text string, adj=1 indicates that the given coordinates are the coordinates to the right of the text string, adj=0.5 that the given coordinates are the middle of the text string
The function identify (x, y, labels) also stops at runtime to wait for the user to click, until the middle mouse button is pressed, and any returned user clicks on the mouse with the number of dots, click on the point labeled. The parameters x and y give the coordinates of each point to be identified. The labels parameter specifies the text label to draw next to a point when clicked, the ordinal number of this point is marked by default, and if you only need to return a value and do not want to draw any tags, you can add a plot=f parameter when calling this function. Note that identify () is different from locator (), locator () returns the coordinates of any click position in the graph, and identify () returns only the ordinal number of the point closest to the click position.
For example, we have coordinates of several points in vectors x and y, and run the following program:

   Attach (CL)
   plot (Height, Weight);
   Identify (Height,weight)

The display is transferred to the graphics window, into the waiting state, the user can click on the special point in the map, the number of the point will be marked next. To end, simply click the middle mouse button or right-click and select Stop. Return the number of points that you clicked on the result:
Warning: The nearest point has been found
Warning: Not a 0.25-foot point.
[1] 1 2 10 15 16

2. hist Histogram

hist (x) as a histogram of vector x. Grouping is automatically determined by default, or the number of groups can be specified with the nclass= parameter, or a grouping point vector is specified with the breaks= parameter. If prob=t is specified, the longitudinal axis displays the density estimate. 3. Stem stem and leaf chart Usage:
Stem (x, scale = 1, width =, atom = 1e-08) Arguments:
x:a numeric vector.
Scale:this controls the plot length.
Width:the desired width of plot.
Atom:a tolerance. References:
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) _the New S
Language_. Wadsworth & Brooks/cole. Examples:
Stem (islands)
Stem (log10 (islands))

Stem (cl$weight, scale = 1, width =, atom = 1e-08) The

  decimal point is 1 digit (s) to the right of |

   4 | 1
   6 | 7
   8 | 3445508
  | 0332233 |
  14
4. BoxPlot Box Line diagram

The parameters in the graph of the box line diagram are as follows:

Example: Made two figure superposition, one for subset= supp = = "VC", the other for subset= supp = = "OJ". The data toothgrowth has two quantity variables (len,dose) and one property variable (supp); Each supp,dose has three values (each of which forms three box charts). Len ~ dose means that box is done by Len.

Data (toothgrowth)
boxplot (len ~ dose, data = toothgrowth, Boxwex = 0.25, at = 1:3-0.2, subset= supp = "VC", col= "ye Llow ", main=" Guinea Pigs ' tooth growth ", xlab=" vitamin C dose mg ", ylab=" tooth Length ", Ylim=c (0,35))
BoxPlot (len ~ do SE, data = toothgrowth, add = TRUE, Boxwex = 0.25, at = 1:3 + 0.2, subset= supp = "OJ", col= "Orange") 
Legend (2, 9, C ( "Ascorbic acid", "orange Juice"), fill = C ("Yellow", "orange"))

BoxPlot (Cl$height~cl$sex,data=cl,col = "Lightgray");

5. Coplot () co-map

Attach (CL)

If z is a numeric variable, coplot () groups The values of Z, and then the values for each group of Z are plotted separately. You can even use Coplot (y~x | x1+x2) to represent each horizontal combination of X1 and x2. The Coplot () and pairs () functions draw a scatter chart by default, but you can specify other low-level drawing functions, such as Lines,panel.smooth, with one panel= parameter. Tsplot (x) draws time series graphs. Multiple parameters when Tsplot (x1, x2, ...) To draw multiple curves and automatically unify the range of curve values. If the parameter is not a time series object, the following subscript 1,2,3 is the horizontal coordinate drawing. 6. Qqnorm () normal QQ diagram and Qqplot () two overall QQ diagram


-Qqnorm (x), Qqline (x), Qqplot (x,y) as a number of points-the number of places.
-Qqnorm (x) is a normal probability for vector x (the longitudinal axis is the order statistic, and the horizontal axis is the standard normal distribution value for the order statistic).
-Qqline (x) draws a fitting curve in addition to a qqnorm (x) figure.
Qqplot (X,y) draws the order statistics of x and y respectively on the x and Y axes to compare the distributions of two variables.

x <-rnorm
y <-rexp (a)
Qqplot (x,y) #可以判断是不是同一个类型的分布

Multi-graph multi-line more than 1 graphs

Par (Mfrow=c (2,2)) #准备画2 The 2 of the 4 figures
plot (compression, distance,main= "Hooke ' s") #只有标题的图
plot (compression, Distance,main= "Hooke ' s", xlab= "x", ylab= "y") #标题 +x,y Mark
Identify (compression,distance) #标出点号码
plot ( Compression, distance,main= "Hooke") #只有标题的图
text (46,120, "f=1/2*k*s") #在指定位写入文字
plot (compression, Distance,main= "Hooke ' s") #只有标题的图
text (Locator (2), "I am here!") #在点击的两个位置写入文字

2 Label

#画图 (logarithmic transformed)
Par (cex=0.7,mex=0.7) #character (CeX) & Margin (MEX) expansion
plot (log (body), log (brain))
text (X=log), Y=log (Brain), Labels=row.names (Animals), adj=1.5) # adj=0 implies left adjusted text

#画图 ( Logarithmic transform) plot (log (body
), log (brain)) identify (log (body
), log (brain), Row.names (Animals))

3 Color Drawing function

View.colours = function () {
plot (1, 1, xlim=c (0,14), Ylim=c (0,3), type= "n", Axes=f, xlab= "", ylab= "")
text (1:6, Rep (2.5,6), paste (1:6), Col=palette () [1:6], cex=2.5)
text (Ten, 2.5, "Default palette", adj=0)
rainchars = C ("R" , "O", "Y", "G", "B", "I", "V")
text (1:7, Rep (1.5,7), Rainchars, Col=rainbow (7), cex=2.5)
text (1.5, "Rainbow") (7) ", adj=0)
cmtxt = substring (" cm.colors ", 1:9,1:9)
# Split" Cm.colors "into its 9 characters
text (1:9, R EP (0.5,9), Cmtxt, Col=cm.colors (9), cex=3)
text (Ten, 0.5, "cm.colors (9)", adj=0)
}
view.colours ()

4 Multi-line advanced low-level function drawing

x <-seq (-pi, pi, len =)
plot (x, sin (x), type = "L", Ylim = C ( -1.2, 1.8), col = 3, lty = 2)
points (x, cos (x) , PCH = 3, col = 4)
lines (x, tan (x), type = "B", lty = 1, pch = 4, col = 6)
title ("Legend (..., lty = C (2,-1, 1), PCH = C ( -1,3,4), merge = TRUE) ", Cex.main = 1.1)
# Note the way the legend is written
legend ( -1, 1.9, C (" Sin "," cos "," tan "), col = C (3,4,6) , lty = C (2,-1, 1), PCH = C ( -1, 3, 4), merge = TRUE, bg= ' gray90 ')

Matplot Drawing

Matplot: Multi-line drawing with matrix columns
Usage:

Matplot (x, y, type = "P", lty = 1:5, LWD = 1, lend = par ("lend"),
        pch = NULL,
        col = 1:6, CeX = null, BG = NA,
        Xlab = null, Ylab = NULL, Xlim = NULL, Ylim = NULL,
        ..., add = FALSE, verbose = getOption ("verbose"))
Require (grdevices)
Matplot (( -4:5) ^2, main = "quadratic") # almost identical to plot (*) sines <-outer
(1:20, 1: 4, function (x, y) sin (x/20 * pi * y))
matplot (sines, pch = 1:4, type = "O", col = Rainbow (Ncol (sines)))
Matplot ( Sines, type = "B", pch = 21:23, col = 2:5, bg = 2:5,
        main = "Matplot (..., pch = 21:23, BG = 2:5)")

5 time series diagram

X=runif (x=ts)
(x,start=1960+ (3/12), frequency=12) #构造时间序列frequency =12 that is, to construct
options (digits=2)
x by month
       Feb, Mar, May   June   Aug   Sep   Oct   Nov   Dec
1960                   0.444 0.849 0.459 0.659 0.277 0.268 0.958 0.926 0.595
1961 0.250 0.769 0.111 0.944 0.593 0.459 0.670 0.331 0.045 0.69 4 0.473 0.227 1962 0.037 0.181 0.562 0.455 0.419 0.968 0.288 0.187 0.143 0.548 0.437
0.280
1963 0.149 0.623 0.93 7 0.108 0.755 0.077 0.963 0.781 0.660 0.458 0.787
1964 0.997 0.650 0.045 0.849 0.018 0.744 0.148 0.964 0.844 0. 660 0.080 0.303 1965 0.954 0.217 0.909 0.658 0.991 0.797 0.020 0.363 0.183 0.332 0.793 0.676
1966 0.459 0.270 0. 813 0.818 0.138 0.780 0.679 0.029 0.553 0.895 0.548 0.480
1967 0.898 0.212 0.299 0.223 0.637 0.167 0.102 0.424 0.438 0.058 0.048 0.474
1968 0.254 0.381 0.532 0.089 0.825 0.337 0.382
Plot (x,main= "Time series")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.