美文网首页
ggplot2学习(3)

ggplot2学习(3)

作者: BioLearner | 来源:发表于2019-11-19 09:02 被阅读0次

    1、Aesthetic mappings

    library(ggplot2)
    p <- ggplot(mtcars, aes(x = mpg, y = wt))
    p + geom_point()
    
    p + geom_point(aes(colour = factor(cyl)))   #cyl为整型​
    #Add aes(colour = factor(cyl))  =====>  aes(x = mpg, y = wt, colour = factor(cyl))
    
    p + geom_point(aes(y = disp))    #将y轴的数据更改为disp,但要注意y轴标签名不会更改
    #Override  aes(y = disp)  ======>  aes(x = mpg, y = disp)  覆盖
    #Remove  aes(y = NULL)  ======>  aes(x = mpg)  删除
    

    关于颜色设置有两种方式: Setting vs Mapping
    Mapping: aes(colour = cut)
    Setting: colour = "blue"
    # Setting
    p + geom_point(colour = "green") 
    
    # Mapping
    p + geom_point(aes(colour = "green")) 
    
    # Mapping
    #倘若希望为指定的颜色
    p + geom_point(aes(colour = I("green"))) 
    # 因为Mapping默认的是一组向量,颜色为内部默认的颜色
    

    分组 grouping
    分组和分面都用于对数据分组,便于观察各自的规律、趋势和模式,不同的是,分组是把图形绘制到一个大的图形中,通过美学特征来区分,而分面是把图形绘制到不同的网格中。
    library(nlme)   #nlme包中有许多数据集
    dat <- Oxboys
    
    Oxboys是牛津大学学生年龄和身高的一个数据集,其中Subject共有26个组,age是标准化后的年龄,Occasion每个Subject有9个样本
    p <- ggplot(dat, aes(age, height, group = Subject)) + geom_line()
    p
    #按照Subject来分组,那些下面应该有26条线,注意分组的依据应当是因子类型
    
    p <- ggplot(dat, aes(age, height, group = 1)) + geom_line()
    p
    # group = 1则不论1改为多大的值,下图中都只会有一条线,相当于分为一组,不加group和group = 1等同
    
    #Different groups on different layers 即将在不同的图层中设置分组
    p <- ggplot(dat, aes(age, height, group = Subject)) + geom_line()
    p + geom_smooth(aes(group = Subject), method = "lm", se = F)
    
    p <- ggplot(dat, aes(age, height, group = Subject)) + geom_line()
    p + geom_smooth(aes(group = 1), method = "lm", se = F, size = 2)
    #不加group和group = 1等同 ,相当于把所有组当作一个整体来构建smooth​
    
    p <- ggplot(dat, aes(age, height, group = 1)) + geom_line()
    p + geom_smooth(aes(group = Subject), method = "lm", se = F)
    
    p <- ggplot(dat, aes(age, height, group = 1)) + geom_line()
    p + geom_smooth(aes(group = 1), method = "lm", se = F)
    
    boysbox <- ggplot(Oxboys, aes(Occasion, height)) + geom_boxplot()   #Occasion为因子类型
    boysbox
    
    boysbox + geom_line(aes(group = Subject),colour = "green")
    

    2、Position adjustments

    ggplot(diamonds,
           aes(clarity, fill = cut)) + geom_bar(position = "stack")
    
    ggplot(diamonds,
           aes(clarity, fill = cut)) + geom_bar(position = "fill")
    
    ggplot(diamonds,
           aes(clarity, fill = cut)) + geom_bar(position = "dodge")
    
    ggplot(diamonds,
             aes(clarity, price, colour = cut)) + geom_point(position = "jitter")
    
    ggplot(diamonds,
           aes(clarity, price, colour = cut)) + geom_point(position = "identity")
    

    欢迎关注微信公众号:BioLearner

    相关文章

      网友评论

          本文标题:ggplot2学习(3)

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