【问题标题】:How to change boxplot categories to unique colors using ggplot?如何使用 ggplot 将箱线图类别更改为独特的颜色?
【发布时间】:2020-06-05 08:37:20
【问题描述】:

您好,我是一名初学者,正在努力弄清楚如何使用 ggplot2 对我的箱线图进行自定义颜色更改?我想将女性更改为栗色,将男性更改为不同的蓝色。

library(ggplot2)

    plot.x <- ggplot(doubleboxplot) + geom_boxplot(aes(sex, x))
    plot.y <- ggplot(doubleboxplot) + geom_boxplot(aes(sex, y))

    plot.x <- layer_data(plot.x)[,1:21]
    plot.y <- layer_data(plot.y)[,1:21]
    colnames(plot.x) <- paste0("x.", gsub("y", "", colnames(plot.x)))
    colnames(plot.y) <- paste0("y.", gsub("y", "", colnames(plot.y)))
    df <- cbind(plot.x, plot.y); rm(plot.x, plot.y)
    df$category <- sort(unique(doubleboxplot$sex))

    df

    library(dplyr)
    library(data.table)
    df.outliers <- df %>%
      select(category, x.middle, x.outliers, y.middle, y.outliers) %>%
      data.table::data.table()
    df.outliers <- df.outliers[, list(x.outliers = unlist(x.outliers), y.outliers = unlist(y.outliers)), 
                               by = list(category, x.middle, y.middle)]

    df.outliers

    p <- ggplot(df, aes(fill = category, color = category)) +

      # 2D box defined by the Q1 & Q3 values in each dimension, with outline
      geom_rect(aes(xmin = x.lower, xmax = x.upper, ymin = y.lower, ymax = y.upper), alpha = 0.3) +
      geom_rect(aes(xmin = x.lower, xmax = x.upper, ymin = y.lower, ymax = y.upper), 
                color = "black", fill = NA) +

      # whiskers for x-axis dimension with ends
      geom_segment(aes(x = x.min, y = y.middle, xend = x.max, yend = y.middle)) + #whiskers
      geom_segment(aes(x = x.min, y = y.lower, xend = x.min, yend = y.upper)) + #lower end
      geom_segment(aes(x = x.max, y = y.lower, xend = x.max, yend = y.upper)) + #upper end

      # whiskers for y-axis dimension with ends
      geom_segment(aes(x = x.middle, y = y.min, xend = x.middle, yend = y.max)) + #whiskers
      geom_segment(aes(x = x.lower, y = y.min, xend = x.upper, yend = y.min)) + #lower end
      geom_segment(aes(x = x.lower, y = y.max, xend = x.upper, yend = y.max)) + #upper end


      xlab("CD8 Activated") + ylab("CD8 CM") +
      coord_cartesian(xlim = c(0.5, 11.5), ylim = c(0.5, 11.5)) +
      theme_classic()


    p + geom_point(doubleboxplot, mapping = aes(x = x, y = y, group = sex, color = sex), inherit.aes = F, alpha = 0.6)

【问题讨论】:

标签: r ggplot2 colors boxplot


【解决方案1】:

另见此常见 ggplot2 颜色列表:http://sape.inf.usi.ch/quick-reference/ggplot2/colour

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 2020-08-28
    • 2018-05-04
    • 2021-10-20
    • 2019-09-03
    相关资源
    最近更新 更多