美文网首页
瑞德学习R语言day05

瑞德学习R语言day05

作者: __method__ | 来源:发表于2021-06-07 16:04 被阅读0次

    散点图

    特性: 两个变量之间的关系分布图

    plot(mtcars$wt, mtcars$mpg)
    

    精细化

     plot(mtcars$wt, mtcars$mpg, xlab = "Car weight", ylab = "Miles per Gallon", col="red", pch=17)
    

    数据拟合

     plot(mtcars$wt, mtcars$mpg, xlab = "Car weight", ylab = "Miles per Gallon", col="red", pch=17)
    abline(lm(mtcars$mpg~mtcars$wt))
    # lm 是线性模型的意思    
    

    简单说一下 lm 函数

    Usage
    lm(formula, data, subset, weights, na.action,
       method = "qr", model = TRUE, x = FALSE, y = FALSE, qr = TRUE,
       singular.ok = TRUE, contrasts = NULL, offset, ...)
    

    -formula:指要拟合的模型形式,

    • data:是一个数据框,包含了用于拟合模型的数据。
    lm(mtcars$mpg~mtcars$wt) 对 mpg和wt进行线性模型分析, 中间用~
    

    abline 函数的作用是在一张图表上添加直线(参考线), 可以是一条斜线,通过x或y轴的交点和斜率来确定位置;也可以是一条水平或者垂直的线,只需要指定与x轴或y轴交点的位置就可以了


    plot

     plot(mtcars)
    

    成对关系图更好看出两个变量之间的 关系

    pairs(mtcars)
    
    plot(~mpg+disp+drat+wt,data = mtcars)
    

    ggplot散点图

    library(ggplot2)
    p = ggplot(mtcars, aes(wt, mpg))
    > p + geom_point()
    
    p = ggplot(mtcars, aes(wt, mpg))
    p + geom_point(aes(colour = factor(cyl)))
    

    传入的不是因子

    p = ggplot(mtcars, aes(wt, mpg))
    p + geom_point(aes(colour = cyl))
    
    p = ggplot(mtcars, aes(wt, mpg))
    p + geom_point(aes(colour = factor(gear)))
    

    下面几个颜色绘制方法等价
    aes(col = x)
    aes(fg = x)
    aes(color = x)
    aes(colour = x)

    p = ggplot(mtcars, aes(wt, mpg))
    p + geom_point(aes(shape = factor(cyl)))
    
    p + geom_point(aes(shape = factor(cyl))) + scale_shape(solid = FALSE)
    
    p = ggplot(mtcars, aes(wt, mpg))
    p + geom_point(aes(size=qsec))
    
    p = ggplot(mtcars, aes(wt, mpg))
    p + geom_point(aes(color=cyl)) + scale_colour_gradient(low = "red")
    
    p = ggplot(mtcars, aes(wt, mpg))
     p + geom_point(aes(color=cyl, size=qsec)) + scale_colour_gradient(low = "red")
    

    plotly

    install.packages("plotly")
    p = plot_ly(mtcars, x=~mpg, y=~wt, type="scatter")
    print(p)
    

    相关文章

      网友评论

          本文标题:瑞德学习R语言day05

          本文链接:https://www.haomeiwen.com/subject/wjmleltx.html