美文网首页
R语言基础学习系列四-用ggplot2 画小提琴图

R语言基础学习系列四-用ggplot2 画小提琴图

作者: 小qqq | 来源:发表于2022-12-01 19:51 被阅读0次

    数据下载来源于:
    https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/10_OneNumSevCatSubgroupsSevObs.csv

    参考代码来自于:Violin plot with ggstatsplot – the R Graph Gallery (r-graph-gallery.com)
    大家可以一起共同学习
    此次用的包是ggstatsplot

    install.packages(c("ggstatsplot","palmerpenguins","tidyverse"))
    library(ggstatsplot)
    library(palmerpenguins)
    library(tidyverse)
    library(rstantools)
    #上传数据
    getwd()
    y <- read.table("D:/biolearning/Rcourse/happy.txt", header=T, sep=",")
    x <- data.frame(y)#转换数据类型
    class(x)#确认数据类型是否转换成功
    #先删除缺失值
    x <- drop_na(x)
    x
    view(x)#查看输入的数据类型
    colnames(x)#查看列名
    #基础绘图
    plt <- ggbetweenstats(
      data = x,
      x = sex,
      y = total_bill
    )
    plt
    

    基础图绘制结果


    Rplot01.png
    #添加标题和标签
    plt <- plt + 
      # Add labels and title
      labs(
        x = "sex",
        y = "total_bill",
        title = "the money"#加标题
      ) + 
      # Customizations
      theme(
        # This is the new default font in the plot
        text = element_text(family = "Roboto", size = 8, color = "black"),
        plot.title = element_text(
          family = "Lobster Two", 
          size = 20,
          face = "bold",
          color = "#2a475e"
        ),
        # Statistical annotations below the main title
        plot.subtitle = element_text(
          family = "Roboto", 
          size = 15, 
          face = "bold",
          color="#1b2838"
        ),
        plot.title.position = "plot", # slightly different from default
        axis.text = element_text(size = 10, color = "black"),
        axis.title = element_text(size = 12)
      )
    plt
    

    添加标签后的图


    Rplot02-lab.png
    # 1. 删除轴刻度
    # 2. 用较浅的颜色更改轴线的默认颜色
    # 3. 删除大部分参考线,只保留主要的水平线
    # 4. 将面板和背景填充设置为相同的浅色
    
    plt <- plt  +
      theme(
        axis.ticks = element_blank(),
        axis.line = element_line(colour = "grey50"),
        panel.grid = element_line(color = "#b4aea9"),
        panel.grid.minor = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_line(linetype = "dashed"),
        panel.background = element_rect(fill = "#fbf9f4", color = "#fbf9f4"),
        plot.background = element_rect(fill = "#fbf9f4", color = "#fbf9f4")
      )
    

    保存照片

    #使用ggsave储存照片格式为png
    ggsave("happy.png", plot = plt,width = 8,height = 8)
    
    
    image.png
    happy.png

    相关文章

      网友评论

          本文标题:R语言基础学习系列四-用ggplot2 画小提琴图

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