簡體   English   中英

刪除ggplot2中geom_boxplot中的邊框

[英]Removing the borders in geom_boxplot in ggplot2

這應該看起來相對簡單但我無法找到允許我這樣做的論據,我已經搜索了Google和Stack以獲得答案。

示例代碼:

library(ggplot2)
library(plotly)

dat <- data.frame(cond = factor(rep(c("A","B"), each=200)), rating = c(rnorm(200),rnorm(200, mean=.8)))

p <- ggplot(dat, aes(x=cond, y=rating, fill=cond)) + geom_boxplot()

p <- ggplotly(p)

這會輸出第一張圖,我想要第二張圖。 圖

我試過包括colour=cond但是擺脫了中位數。

兩個可能的黑客需要考慮,使用與Marco Sandri的答案相同的數據集。

哈克1 如果你真的不需要它在plotly中工作,只需靜態ggplot圖像:

ggplot(dat, aes(x=cond, y=rating, fill=cond)) + 
  geom_boxplot() +
  geom_boxplot(aes(color = cond),
               fatten = NULL, fill = NA, coef = 0, outlier.alpha = 0,
               show.legend = F)

哈克1

這將原始的boxplot覆蓋了一個版本,該版本基本上是外框的輪廓,隱藏中位數( fatten = NULL ),填充顏色( fill = NA ),whiskers( coef = 0 )和outliers( outlier.alpha = 0 )。

但是,它似乎與情節不太一致。 我用ggplot2的開發版測試了它(如圖所示)無濟於事。 見下面的輸出:

破解1劇情

黑客2 如果你需要它在劇情上工作:

ggplot(dat %>%
         group_by(cond) %>%
         mutate(rating.IQR = case_when(rating <= quantile(rating, 0.3) ~ quantile(rating, 0.25),
                                       TRUE ~ quantile(rating, 0.75))), 
       aes(x=cond, y=rating, fill=cond)) + 
  geom_boxplot() +
  geom_boxplot(aes(color = cond, y = rating.IQR),
               fatten = NULL, fill = NA)

(ggplot輸出與上面相同)

plotly似乎不理解coef = 0output.alpha = 0命令,因此這個hack創建了y變量的修改版本,這樣P30以下的所有內容都設置為P25,上面的所有內容都設置為P75。 這會創建一個沒有異常值,沒有胡須的箱線圖,並且中位數與P75的上限限制一起。

它更麻煩,但它的作用是:

Hack 2 plotly

這是一個基於grobs的優雅解決方案:

set.seed(1)
dat <- data.frame(cond = factor(rep(c("A","B"), each=200)), 
                  rating = c(rnorm(200),rnorm(200, mean=.8)))

library(ggplot2)
library(plotly)
p <- ggplot(dat, aes(x=cond, y=rating, fill=cond)) + geom_boxplot() 

# Generate a ggplot2 plot grob
g <- ggplotGrob(p)

# The first box-and-whiskers grob
box_whisk1 <- g$grobs[[6]]$children[[3]]$children[[1]]
pos.box1 <- which(grepl("geom_crossbar",names(box_whisk1$children)))
g$grobs[[6]]$children[[3]]$children[[1]]$children[[pos.box1]]$children[[1]]$gp$col <-
  g$grobs[[6]]$children[[3]]$children[[1]]$children[[pos.box1]]$children[[1]]$gp$fill

# The second box-and-whiskers grob    
box_whisk2 <- g$grobs[[6]]$children[[3]]$children[[2]]
pos.box2 <- which(grepl("geom_crossbar",names(box_whisk2$children)))
g$grobs[[6]]$children[[3]]$children[[2]]$children[[pos.box2]]$children[[1]]$gp$col <-
  g$grobs[[6]]$children[[3]]$children[[2]]$children[[pos.box2]]$children[[1]]$gp$fill

library(grid)
grid.draw(g)

在此輸入圖像描述

PS據我所知,上面的代碼不能用於生成plotly圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM