zoukankan      html  css  js  c++  java
  • R语言画图

    转http://www.cnblogs.com/jiangmiaomiao/p/6991632.html

    0 引言

      R支持4种图形类型: base graphics, grid graphics, lattice graphics,  ggplot2。其中,Base graphics是R的默认图形系统。

    1  基本图形函数plot()

    plot()命令中的type参数用于明确图形如何绘制,具体type值使用如下:

    • "p" for "points"
    • "l" for "lines"
    • "o" for "overlaid" (例如,和点重叠的线)
    • "s" for "steps"

    type=“n”这个特殊选项,可用于在坐标轴上绘制来自多个源的数据。

    例如:

    plot(x,y,xlab="",ylab="",pch=2,col="red")

    pch:数据点形状

    col:数据点颜色

    2 其他类型的图形函数

    (1)饼图:pie()

    (2)直方图是表示数字变量分布范围的最常用方式

    hist():base R, 记录每个区域出现的次数的直方图

    truehist()  :MASS package,规整数值给出概率密度的估计。

    密度图可看做平滑直方图,例如line(density())

     直方图和密度图的一个局限是,难以观察数据是否符合高斯分布(正态分布)

    使用qqplot()观察数据是否符合高斯分布(正态分布)

     (3)sunflowerplot() 函数

    散点图中的每个点对应一个(x, y)对,如果同一(x, y)对出现多次,点会重叠,在散点图中无法观察到。这个问题有很多解决方法,例如 jittering(扰动), 对每个x、y添加小的随机值,因此重复点将作为附近点簇集出现。另一个有效方法是 sunflowerplot()函数,, 每个重复值由太阳花展示,每个花瓣代表某个数据点的一次重复

     (4)boxplot()函数

    boxplot()函数表示数字变量y对应变量x的每个唯一值的分布情况。x变量不应有太多唯一值,多于10个会使得图形难以观察。

    可选参数:

    varwidth  允许箱型图宽度随变量变化来显示不同数据子集的大小。

    log 允许y值的对数变换

    las 允许更多可读的轴标签

    # 创建一个y轴取对数和水平标签的变量宽度箱型图

    boxplot(y ~ x data = Boston, varwidth = TRUE, log = "y", las = 1)

     (5)马赛克图mosaicplot()

    马赛克图可看做是分类变量间的散点图,也可以用于观察数字型变量的关系。

     (6)bagplot()

    一个简单的箱型图基于五个数字给出了一个数字变量的变动范围:

    最大值、最小值、中间值、上、下四分位数。

    标准箱型图通过以上数字中的三个计算名义上的数据范围,将超出该范围的点标示为极端值,用独立的点表示。包型图表示两个数字变量的关系,二维的包对应标准箱型图中的箱,并标示出极端值。

     (7)corrplot()函数图示相关性矩阵

    相关性矩阵是获取多个数字变量间关系的初步看法的有效工具。

    在图中,瘦长的椭圆表示指定的变量间存在较大相关性,近乎圆形表示相关性近似为0.

    # Load the corrplot library for the corrplot() function
    library(corrplot)

    # Compute the correlation matrix for these variables
    corrMat <- cor(data)

    # Generate the correlation ellipse plot
    corrplot(corrMat,method="ellipse")

     (8)构造和绘制rpart() 模型

    决策树容易观察和解释,是预测模型的一种常用方式。

    # Load the rpart library

    library(rpart)

    # Fit an rpart model to predict medv from all other Boston variables
    tree_model <- rpart(medv~.,data=Boston)

    # Plot the structure of this decision tree model
    plot(tree_model)

    # Add labels to this plot
    text(tree_model,cex=0.7)

     (9)使用symbol()函数来显示多于两个变量之间的关系。

    散点图显示一个数字变量是如何随第二个数字变量改变。symbols()允许扩展散点图来显示其他变量的影响。circles参数用来创建一个气泡图,每个数据点由一个圆圈表示,半径基于第三个变量值。

    # Call symbols() to create the default bubbleplot
    symbols(Cars93$Horsepower, Cars93$MPG.city,
    circles = Cars93$Cylinders)

    # Repeat, with the inches argument specified
    symbols(Cars93$Horsepower, Cars93$MPG.city,
    circles = Cars93$Cylinders,
    inches = 0.2)

    (10)点阵图示例

    # Load the lattice package
    library(lattice)

    # Use xyplot() to construct the conditional scatterplot
    xyplot(calories ~ sugars | shelf, data = UScereal)

     

    3 环境函数par()

    par()函数用于设置图形参数,且参数一直保持有效直到被下一个par()命令重置。

    空参数的par()命令返回当前所有图形参数值。

    例:创建一个一排2列的图形阵列

    par(mfrow = c(1, 2))

     

     4 为图形添加细节

    (1)line()在已存在的图中添加线条

    # Create the numerical vector x
    x <- seq(0, 10, length = 200)

    # Compute the Gaussian density for x with mean 2 and standard deviation 0.2
    gauss1 <- dnorm(x, mean = 2, sd = 0.2)

    # Compute the Gaussian density with mean 4 and standard deviation 0.5
    gauss2 <- dnorm(x, mean = 4, sd = 0.5)

    # Plot the first Gaussian density
    plot(x, gauss1, type = "l", ylab = "Gaussian probability density")

    # Add lines for the second Gaussian density
    lines(x, gauss2, lty = 2, lwd = 3)

    (2) points()

    在plot() 或 points()中,pch参数可基于数据中的变量来设置。

    # Create an empty plot using type = "n"
    plot(mtcars$hp, mtcars$mpg, type = "n",
    xlab = "Horsepower", ylab = "Gas mileage")

    # Add points with shapes determined by cylinder number
    points(mtcars$hp, mtcars$mpg, pch = mtcars$cyl)

    # Create a second empty plot
    plot(mtcars$hp, mtcars$mpg, type = "n",
    xlab = "Horsepower", ylab = "Gas mileage")

    # Add points with shapes as cylinder characters
    points(mtcars$hp, mtcars$mpg, 
    pch = as.character(mtcars$cyl))

    (3)为线性回归模型添加趋势线

    abline()在已存在图形中添加直线。这条线由截距参数a和斜率参数b来规定。

    例如 abline(a = 0, b = 1) 添加了一条截距为0的等距参考线。

    还可通过线性回归模型来规定参数

    # Build a linear regression model for the whiteside data
    linear_model <- lm(Gas ~ Temp, data = whiteside)

    # Create a Gas vs. Temp scatterplot from the whiteside data
    plot(whiteside$Temp, whiteside$Gas)

    # Use abline() to add the linear regression line
    abline(linear_model, lty = 2)

    (4)使用text() 标记图形特性

    参数:

    • x 规定x变量的值
    • y 规定y变量的值
    • labels 规定x-y键值对的标签。

    adj  取0-1之间的任意值,小于0,字在x位置的右边;大于1,字在x位置的左边

    cex 字体大小与默认值的比例

    font  字体

    srt参数旋转字体

    (5) legend()

    为图形添加解释文字

    legend("topright", pch = c(17, 1), legend = c("Before", "After"))

    (6)使用 axis() 添加定制轴

    当需要使用自己的轴标签时,可在绘图函数中设置参数axes = FALSE阻止生成默认轴,再调用axis生成定制轴

    axis()的参数:

    side  表示轴位置,1底部,2左边,3顶部,4右边

    at  在哪些点绘制刻度

    labels  每个刻度的标签

    # Create a boxplot of sugars by shelf value, without axes
    boxplot(sugars ~ shelf, data = UScereal,
    axes = FALSE)

    # Add a default y-axis to the left of the boxplot
    axis(side = 2)

    # Add an x-axis below the plot, labelled 1, 2, and 3
    axis(side = 1)

    # Add a second x-axis above the plot
    axis(side = 3, at = c(1, 2, 3),
    labels = c("floor", "middle", "top"))

    (7)用supsmu()添加平滑趋势曲线

    一些散点图明显不是线性趋势,需要使用曲线来突出数据的行为。参数bass控制趋势曲线的平滑度,默认值为0,按时较大值(最大10)可生成更平滑的曲线。

    # Create a scatterplot of MPG.city vs. Horsepower
    plot(Cars93$Horsepower, Cars93$MPG.city)

    # Call supsmu() to generate a smooth trend curve, with default bass
    trend1 <- supsmu(Cars93$Horsepower, Cars93$MPG.city)

    # Add this trend curve to the plot
    lines(trend1)

    # Call supsmu() for a second trend curve, with bass = 10
    trend2 <- supsmu(Cars93$Horsepower, Cars93$MPG.city,
    bass = 10)

    # Add this trend curve as a heavy, dotted line
    lines(trend2, lty = 3, lwd = 2)

     

    5 判断散点图数量是否过多

    matplot()在同一坐标轴中生成多个散点图。散点图中的点默认由1到n的数字表示,n是包含的散点图的总数。

    # Set up a two-by-two plot array
    par(mfrow = c(2, 2))

    # Use matplot() to generate an array of two scatterplots
    matplot(df$calories, df[, c("protein", "fat")], 
    xlab = "calories", ylab = "")

    # Add a title
    title("Two scatterplots")

    # Use matplot() to generate an array of three scatterplots
    matplot(df$calories, df[, c("protein", "fat", "fibre")], 
    xlab = "calories", ylab = "")

    # Add a title
    title("Three scatterplots")

    # Use matplot() to generate an array of four scatterplots
    matplot(df$calories, 
    df[, c("protein", "fat", "fibre", "carbo")], 
    xlab = "calories", ylab = "")

    # Add a title
    title("Four scatterplots")

    # Use matplot() to generate an array of five scatterplots
    matplot(df$calories, 
    df[, c("protein", "fat", "fibre", "carbo", "sugars")], 
    xlab = "calories", ylab = "")

    # Add a title
    title("Five scatterplots")

     

    6 判断文字数量是否过多 

    wordcloud()根据出现的频率来展示不同大小的文字。频率更高的文字较大,较少出现的文字字体较小。

    第一个参数: 文字的字符向量

    第二个参数: 每个文字出现的次数的数字向量

    scale: 是一个两元数字向量,表示最大文字和最小文字的相对大小

    min.freq  规定文字云只包含至少出现min.freq次的文字,默认值是3.

    # Create the wordcloud of all model names with smaller scaling
    wordcloud(words = names(model_table), 
    freq = as.numeric(model_table), 
    scale = c(0.75, 0.25), 
    min.freq = 1)

     

    7 用多种图形来观察数据

    # Set up a two-by-two plot array
    par(mfrow = c(2, 2))

    # Plot the raw duration data
    plot(geyser$duration, main = "Raw data")

    # Plot the normalized histogram of the duration data
    truehist(geyser$duration, main = "Histogram")

    # Plot the density of the duration data
    plot(density(geyser$duration), main = "Density")

    # Construct the normal QQ-plot of the duration data
    qqPlot(geyser$duration, main = "QQ-plot")

     

    8 构造和展示布局矩阵

    1、使用matrix()生成一个图形位置的矩阵,然后用layout()建立一个图形阵列,layout.show()用于验证图形阵列的形状。

    # Define row1, row2, row3 for plots 1, 2, and 3
    row1 <- c(0, 1)
    row2 <- c(2, 0)
    row3 <- c(0, 3)

    # Use the matrix function to combine these rows into a matrix
    layoutMatrix <- matrix(c(row1, row2, row3), 
    byrow = TRUE, nrow = 3)

    # Call the layout() function to set up the plot array
    layout(layoutMatrix)

    # Show where the three plots will go 
    layout.show(3)

    2 创建图形阵列

    # Set up the plot array
    layout(layoutMatrix)

    # Construct the vectors indexB and indexA
    indexB <- which(whiteside$Insul == "Before")
    indexA <- which(whiteside$Insul == "After")

    # Create plot 1 and add title
    plot(whiteside$Temp[indexB], whiteside$Gas[indexB],
    ylim = c(0, 8))
    title("Before data only")

    # Create plot 2 and add title
    plot(whiteside$Temp, whiteside$Gas,
    ylim = c(0, 8))
    title("Complete dataset")

    # Create plot 3 and add title
    plot(whiteside$Temp[indexA], whiteside$Gas[indexA],
    ylim = c(0, 8))
    title("After data only")

    3、创建不同大小图形的阵列

    # Create row1, row2, and layoutVector
    row1 <- c(1, 0, 0)
    row2 <- c(0, 2, 2)
    layoutVector <- c(row1, rep(row2, 2))

    # Convert layoutVector into layoutMatrix
    layoutMatrix <- matrix(layoutVector, byrow = TRUE, nrow = 3)

    # Set up the plot array
    layout(layoutMatrix)

    # Plot scatterplot
    plot(Boston$rad, Boston$zn)

    # Plot sunflower plot
    sunflowerplot(Boston$rad, Boston$zn)

     

    九、图形函数可返回有用信息

     barplot() 函数除了创建图形, 还可以返回图中每个条形的中心位置的数字向量。

    当我们想在水平条形图的条形上放置文字时,这个返回值很有用。因此可获取该返回值并在text()函数中作为y参数。使我们可以在任意x位置将文字放置在每个水平条的中间。

    # Create a table of Cylinders frequencies
    tbl <- table(Cars93$Cylinders)

    # Generate a horizontal barplot of these frequencies
    mids <- barplot(tbl, horiz = TRUE, 
    col = "transparent",
    names.arg = "")

    # Add names labels with text()
    text(20, mids, names(tbl))

    # Add count labels with text()
    text(35, mids, as.numeric(tbl))

     

    十、将图形结果保存为文件

    png文件易于分享和作为email附件。使用png()函数生成和命名一个png文件,建立起一个特殊的环境可获取所有的图形输出直到使用dev.off()指令退出该环境。

    # Call png() with the name of the file we want to create
    png("bubbleplot.png")

    # Re-create the plot from the last exercise
    symbols(Cars93$Horsepower, Cars93$MPG.city,
    circles = Cars93$Cylinders,
    inches = 0.2)

    # Save our file and return to our interactive session
    dev.off()

    # Verify that we have created the file
    list.files(pattern = "png")

     

    十一图形的颜色

    1 12种推荐颜色

    IScolors <- c("red", "green", "yellow", "blue","black", "white", "pink", "cyan","gray", "orange", "brown", "purple")

    2 使用颜色来增强气泡图

    # Iliinsky and Steele color name vector
    IScolors <- c("red", "green", "yellow", "blue",
    "black", "white", "pink", "cyan",
    "gray", "orange", "brown", "purple")

    # Create the colored bubbleplot
    symbols(Cars93$Horsepower, Cars93$MPG.city, 
    circles = Cars93$Cylinders, inches = 0.2, 
    bg = IScolors[as.numeric(Cars93$Cylinders)])

    使用颜色来增强堆积条形图

    barplot函数默认为每个条图的不同分段使用深浅不同的灰色

    # Create a table of Cylinders by Origin
    tbl <- table(Cars93$Cylinders, Cars93$Origin)

    # Create the default stacked barplot
    barplot(tbl)

    # Enhance this plot with color
    barplot(tbl, col = IScolors)

  • 相关阅读:
    SQL Server 锁升级(Lock Escalations)
    Linux 输入与输出重定向详解
    MySQL DDL的成本高低
    spring 学习-bean创建-refresh方法
    spring 学习-bean创建-scan扫描bean
    spring 学习-bean创建-重要类介绍
    zkclient大量节点事件导致CPU飙升
    spring 学习-bean创建-重要类介绍
    ElasticSearch 按值排序
    Redis set 详解
  • 原文地址:https://www.cnblogs.com/babyfei/p/9031559.html
Copyright © 2011-2022 走看看