• ggplot2图形简单绘制


    一、所用函数

    1. sort、rank、order用法

    #在R中,和排序相关的函数主要有三个:sort(),rank(),order()。 
    #sort(x)是对向量x进行排序,返回值排序后的数值向量。
    #rank()是求秩的函数,它的返回值是这个向量中对应元素的“排名”
    #order()的返回值是对应“排名”的元素所在向量中的位置。
    x<-c(97,93,85,74,32,100,99,67)
    sort(x)
    [1]  32  67  74  85  93  97  99 100
    order(x)
    [1] 5 8 4 3 2 1 7 6
    rank(x)
    [1] 6 5 4 3 1 8 7 2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2. arrange 用法

    arrange()函数用于在逻辑表达式下对表行进行重新排序。是plyr包中的,对数据框按列排序,仍返回数据框 。参数如下,
    - x : 要重新排序的数据集
    - expr :带有列名的逻辑表达式
    - 示例

    # Create a data frame 
    d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),  
                     age = c(7, 5, 9, 16) )     
    # Arranging name according to the age 
    d.name <- arrange(d, age) 
    print(d.name) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在这里插入图片描述

    3. reorder用法

    reorder用在绘图中,比如ggplot中绘条形图,可使x轴按y轴数值大小排序
    比如横轴为age,纵轴为money,可写为:aes(x=reorder(age,money),y=money),即按money对age排序

    4. cumsum 用法

    cumsum函数用于计算向量的累积和

    # Creating Vectors
    x1 <- c(2, 4, 5, 7)
    x2 <- c(2.4, 5.6, 3.4)
      
    # Calling cumsum() Function
    cumsum(x1)
    cumsum(x2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    5. interaction用法

    interaction函数产生不同变量之间的交互,假设我有3个不同的因素要考虑: a,b和c,并且我想创建一个新的变量,以显示这三个因素对于特定观察的特定组合。sep参数更改字符’.’
    在这里插入图片描述

    二、散点图

    数据集选择R中自带的mrcars 数据集

    1. 使用str() 函数观察属性类型
      在这里插入图片描述
      全部变量为连续型

    2. 颜色变量为连续性

      • mtcars为数据集
      • x轴选择wt变量,y轴选择mpg变量
      • 设置cyl变量为颜色变量
      ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point(aes(color=cyl))
      
      • 1

      在这里插入图片描述

    3. 颜色变量为离散变量

      • 使用factor() 函数将连续值转换为因子型
      ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point(aes(color=factor(cyl)))
      
      • 1

      在这里插入图片描述

    三、折线图、直方图、箱线图

    • 折线图:ggplot(pressure, aes(temperature, pressure)) + geom_line() + geom_point()

    • 直方图 : 特殊的直方图,连续变量的分布,横坐标分段来统计分段内个数

      # bindwidth为横坐标分段的组距
      ggplot(mtcars, aes(mpg)) + geom_histogram(binwidth = 3)
      
      • 1
      • 2
    • 箱线图

      ggplot(data = ToothGrowth, aes(supp, len)) + geom_boxplot()
      # 分组箱线图用interaction函数
      ggplot(data = ToothGrowth, aes(interaction(supp,dose), len)) + geom_boxplot()
      
      • 1
      • 2
      • 3

    四、柱状图

    1. 单一变量 (统计单一变量的属性值分布)

    ggplot(mtcars, aes(factor(cyl))) + geom_bar()

    • 当绘制柱状图时,只传一个变量参数时,即为统计当前变量中各个属性值的个数
    • geom_bar() 函数中stat参数默认为count
    • cyl变量经过factor操作 : 若x轴为连续值则会不连贯,例如下图
      在这里插入图片描述
      • 绘图结果如下

    在这里插入图片描述

    2. 单一变量+fill (列联表)

    设置填充颜色fillCultivar变量
    ggplot(cabbage_exp, aes(Date, fill = Cultivar)) + geom_bar(position = 'dodge')
    其中,geom_barposition 参数如下,

    • identity : 不堆积,组内前后堆叠
    • stack : 堆积,默认值
    • dodge : 分散
    • fill : 按比例堆积
      在这里插入图片描述

    3. 两个变量

    ggplot(BOD, aes(factor(Time), demand)) + geom_bar(stat = 'identity'),相比统计单个变量,

    • aes函数中为两个变量
    • geom_bar函数中stat设置为 identity
    • 绘制结果如下
      在这里插入图片描述

    4. 两个变量+fill

    # 筛选Change>40的条目
    upc <- subset(uspopchange, rank(Change)>40)
    ggplot(upc, aes(Abb, Change, fill = Region)) + geom_bar(stat = 'identity')
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    5. 修改描边和填充颜色

    ggplot(pg_mean, aes(group, weight)) + geom_bar(stat = 'identity', fill = 'lightblue', color = 'black')

    • 描边设置 color 参数
    • 填充颜色为 fill 参数

    6. 修改颜色模式

    # 通过scale_fill_brewer() 修改填充颜色模式
    # 通过scale_colour_brewer() 修改描边颜色模式
    ggplot(cabbage_exp, aes(Date,Weight,fill = Cultivar)) + 
                        geom_bar(position = 'dodge', stat = 'identity', color = 'black') + 
                        scale_fill_brewer(palette = 'Pastel1')
    # 查看调色板 
    RColorBrewer::display.brewer.all()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    7. 柱状图按照高低排序

    • 使用reorder函数进行排序 : aes(x=reorder(Abb, Change),y=Change, fill = Region))
    • scale_fill_manual 函数自行设置颜色
    • xlab函数设置x轴标签
    # 使用reorder函数,将其按高度进行排序
    ggplot(upc, aes(x=reorder(Abb, Change),y=Change, fill = Region)) + geom_bar(stat = 'identity') + 
                                                scale_fill_manual(values = c('#669933','#FFCC66')) + 
                                                xlab('State') 
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    7. 调节柱宽

    7.1 普通柱状图

    #---------------------------------------#
    # 调节柱宽是调节柱子本身的宽度
    # width 参数默认为0.9,最大为1,最小为0
    # 柱宽变大,柱间距就会变小
    #---------------------------------------#
    ggplot(pg_mean, aes(x=group, y=weight)) + geom_bar(stat = 'identity', width = 0.2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在这里插入图片描述

    7.2 分组柱状图

    #---------------------------------------#
    # 分组条形图调节柱宽
    # 默认同一分组之间的柱是没有间距的
    # 		在geom_bar 参数中设置: position=position_dodge()
    # width表示柱宽,默认0.9,最大为1,最小为0
    # position_dodge表示组内间距,默认为0.9,越大表示间距越大
    #---------------------------------------#
    ggplot(cabbage_exp, aes(Date, Weight, fill=Cultivar)) + 
                        geom_bar(stat = 'identity', width = 0.9, position = position_dodge(0.5))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

    8. 添加文本标签

    8.1 普通柱状图

    #-------------------------------------------------#
    # 柱状图加文字标签
    # 使用geom_text
    #     1. 参数aes():设置标签变量
    #     2. 参数vjust: 0表示标签底部与柱状图顶部对齐
    #                   正数表示在柱状图顶部下方
    #                   负数表示在柱状图顶部上方
    #        参数colour:表示文本颜色 
    #------------------------------------------------#
    # interaction() 函数的使用
    # > interaction(cabbage_exp$Date,cabbage_exp$Cultivar)
    # [1] d16.c39 d20.c39 d21.c39 d16.c52 d20.c52 d21.c52
    # Levels: d16.c52 d20.c52 d21.c52 d16.c39 d20.c39 d21.c39
    ggplot(cabbage_exp, aes(interaction(Date, Cultivar),Weight)) + 
                              geom_bar(stat = 'identity') + 
                              geom_text(aes(label=Weight), vjust=1.5, colour = 'white')
    # 防止标签超出图例,可以调整y轴的范围
    # 方法1:ylim()函数
    ggplot(cabbage_exp, aes(interaction(Date, Cultivar),Weight)) + 
                              geom_bar(stat = 'identity') + 
                              geom_text(aes(label = Weight), vjust = -0.2) + 
                              ylim(0, max(cabbage_exp$Weight) * 1.05)
    # 方法2 : 不使用vjust参数,而是以weight为基准,调节y值,图形高度自动适配
    #     其中y值为文本标签的高度
    ggplot(cabbage_exp, aes(interaction(Date, Cultivar),Weight)) + 
                              geom_bar(stat = 'identity') + 
                              geom_text(aes(y = Weight - 0.1, label = Weight))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    8.2 分组柱状图

    # 分组柱状图加标签,需要设定 position_dodge():调节同一分组的间距,以调整字体的合适位置
    # 在geom_text中设置position = position_dodge(.9) 为了调节柱宽和组间距
    # width表示柱宽,默认0.9,最大为1,最小为0
    # position_dodge表示组内间距,默认为0.9,越大表示间距越大
    ggplot(cabbage_exp, aes(Date,Weight, fill = Cultivar)) + 
                             geom_bar(stat = 'identity', position = 'dodge',width = 0.9) + 
                             geom_text(aes(label=Weight), 
                                       vjust = 1.5, 
                                       color= 'white',
                                       position = position_dodge(.9),
                                       size=7)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    8.3 堆积柱状图

    #堆积柱状图添加label
    library(plyr)
    # arrange () R语言中的函数用于在列名作为传递给函数的表达式的帮助下对表行进行重新排序
    ce <- arrange(cabbage_exp, Date, Cultivar)
    # cumsum() 函数用于计算累加和
    ce <- ddply(ce, .(Date), transform, label_y=cumsum(Weight))
    ce$Cultivar <- factor(ce$Cultivar, levels = c('c39','c52'))
    ggplot(ce, aes(x=Date, y=Weight, fill=Cultivar)) + 
                                geom_bar(stat = 'identity') + 
                                geom_text(aes(y=label_y-0.1, label=Weight), colour='white')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    8.4 添加单位

    # 添加单位
    # format()函数的格式化为特定样式: nsmall参数为小数点右边位数,不够补零
    ggplot(ce, aes(Date, Weight, fill=Cultivar)) + 
                                geom_bar(stat = 'identity',color='black') + 
                                geom_text(aes(y=label_y - 0.1,
                                              label=paste(format(Weight, nsmall=2),'kg')
                                              ), size=4 )+
                                scale_fill_brewer(palette = 'Pastel1')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 相关阅读:
    JVM | 命令行诊断与调优 jhsdb jmap jstat jps
    MPViT : Multi-Path Vision Transformer for Dense Prediction
    《大厂高并发分布式锁从入门到实战》第2讲之redis分布式锁
    Vue知识点整理(待更新)
    AR导览软件定制开发方案
    Elasticsearch:使用 LangChain 对话链和 OpenAI 的聊天机器人
    云计算 - 阿里云最佳云上实践介绍 卓越架构
    二叉树(tree)相关数据结构和算法
    MongoDB副本集集群搭建
    axios的请求中断和请求重试
  • 原文地址:https://blog.csdn.net/m0_45210226/article/details/127931623