更改 ggboxplot 框轮廓颜色

时间:2021-05-27 10:41:12

标签: r ggplot2 dplyr tidyverse

如何为箱线图条添加黑色轮廓?如果我指定 color="black" 文本会在彼此之上。我也想把文字颜色改成黑色

数据:

COUNTRY  ACTUAL    YEAR 
<chr>    <<dbl>    <dbl>   
1 U.S.A.  9.42     1996     
2 U.S.A.  208      1998  
3 U.S.A.  454.     1996  
4 U.S.A.  21.2     1996  
5 U.S.A.  566      1997  
6 Mexico  370.     1995  
7 U.S.A.  845.     1996  
8 Canada  492      1998  
9 U.S.A. 1352.     1998  
10 U.S.A.  103.    1996 
...

代码:

df %>% 
  select(YEAR, COUNTRY, ACTUAL) %>% 
  mutate(YEAR = as.factor(YEAR)) %>%
  group_by(COUNTRY, YEAR) %>% 
  ggsummarystats(
    ., x = c("COUNTRY"), y = c("ACTUAL"),
    palette=custom_pal,
    ggfunc = ggboxplot,
    color="YEAR",
    fill = "YEAR", 
    summaries = c("n", "mean", "median", "min", "max")
  )

制作图片

Example

如果我编辑

color=rep("black", 12)

然后生成的图片是这样的: Error

否则看起来不错,但汇总统计数据相互叠加,R 发出警告:

Warning messages:
1: In if (color %in% names(data) & is.null(add.params$color)) add.params$color <- color :
  the condition has length > 1 and only the first element will be used
2: In if (color %in% colnames(df)) { :
  the condition has length > 1 and only the first element will be used

1 个答案:

答案 0 :(得分:1)

在将输出分配给一个对象后,您可以分别更改两个图的颜色,我们称之为 p。更改 p$main.plot 会更改绘图轮廓和误差线,更改 p$summary.plot 会更改文本颜色。

p <- df %>% 
    select(YEAR, COUNTRY, ACTUAL) %>% 
    mutate(YEAR = as.factor(YEAR)) %>%
    group_by(COUNTRY, YEAR) %>% 
    ggsummarystats(
        ., x = c("COUNTRY"), y = c("ACTUAL"),
        palette=custom_pal,
        ggfunc = ggboxplot,
        color="YEAR",
        fill = "YEAR", 
        summaries = c("n", "mean", "median", "min", "max")
    )

n <- length(unique(df$YEAR))
p$main.plot <- p$main.plot + scale_color_manual(values=rep("black", n))
p$summary.plot <- p$summary.plot + scale_color_manual(values=rep("black", n))
p