ggplot2 分组箱线图图绘制方法

    xiaoxiao2022-06-27  157

    1. 载入软件包

    这里使用R语言的data.table和ggplot2

    library(ggplot2) library(data.table)

    2. 生成模拟数据

    生成示例数据

    library(data.table) library(ggplot2) dat <- data.table(Spring = c(runif(9,0,1),2), Summer = runif(10,0,1), Autumn = runif(10,0,1), Winter = runif(10,0,1)) dat1 = melt(dat)

    数据如下:

    variable value 1: Spring 0.35080952 2: Spring 0.54117242 3: Spring 0.57099138 4: Spring 0.69833364 5: Spring 0.17191075 6: Spring 0.63691289 7: Spring 0.40214424 8: Spring 0.97314831 9: Spring 0.83956778 10: Spring 2.00000000 11: Summer 0.47840804 12: Summer 0.79554135 13: Summer 0.15929476 14: Summer 0.45459106 15: Summer 0.36670243 16: Summer 0.02211403 17: Summer 0.28918663 18: Summer 0.63833289 19: Summer 0.80307539 20: Summer 0.89594080 21: Autumn 0.90843733 22: Autumn 0.43163801 23: Autumn 0.25398825 24: Autumn 0.66496326 25: Autumn 0.29471913 26: Autumn 0.57182528 27: Autumn 0.51998086 28: Autumn 0.48036170 29: Autumn 0.35763278 30: Autumn 0.36079394 31: Winter 0.50301352 32: Winter 0.80367454 33: Winter 0.92260861 34: Winter 0.25098717 35: Winter 0.67010922 36: Winter 0.81587109 37: Winter 0.16946031 38: Winter 0.41868416 39: Winter 0.03333256 40: Winter 0.40031857 variable value

    3. 生成分组箱线图

    要点

    data=dat1 # 定义数据aes(x = variable, y = value) # 定义x轴和y轴geom_boxplot() #定义箱线图 ggplot(data=dat1,aes(x=variable,y=value)) +geom_boxplot()

    为不同的箱线图添加颜色

    ggplot(data=dat1,aes(x=variable,y=value,colour=variable)) +geom_boxplot()


    最新回复(0)