【问题标题】:R ggplot background color boxplotR ggplot 背景颜色箱线图
【发布时间】:2018-11-21 16:43:22
【问题描述】:

我有一个像这样的数据框:

value = runif(n = 1000) 
type = rep(c("a","b","c","d"),250) 
type2 = rep(c("a","b"),500) 
number = sample(1:4, 1000, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
feature = c(rep("small",500),rep("big",500)) 
allResults <- data.frame(value,type,type2,number,feature)

我想用 type2 值为箱线图的背景着色。如果我使用填充和列,它不是很清楚。如果可能的话,我认为背景颜色更直观。

library("ggplot2")
ggplot(allResults, aes(y=value, x=type)) + geom_boxplot(alpha=.3, aes(fill = type,col=type2)) +
  ggtitle("comparison") + facet_grid(feature ~ number) +
  theme(legend.position = "bottom",axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_y_continuous(breaks =  seq(0, 1, by = 0.05),limits = c(0,1))

这是我目前的结果:

我已经看到可以使用 geom_rect() 为背景着色,但我不明白如何应用。

【问题讨论】:

  • 你只想用type2填充每个箱线图的背景?
  • 是的,我想像这样给背景面板上色:i.stack.imgur.com/fqyah.jpg
  • 这不是更有意义(所以背景颜色不会与type重叠):ggplot(allResults, aes(y=value, x=type)) + geom_boxplot(alpha=.3, aes(fill = type2, col=type2)) + ggtitle("comparison") + facet_grid(feature ~ number) + theme(legend.position = bottom",axis.text.x = element_text(angle = 90, hjust = 1)) + scale_y_continuous(breaks = seq(0, 1, by = 0.05),limits = c(0,1))
  • 为什么?如果我可以填充为什么我不能使用背景颜色?这是正确的例子:i.stack.imgur.com/CpM0p.gif

标签: r ggplot2 boxplot


【解决方案1】:

您可以使用geom_rect 并设置您的部门。我最初将ab 作为您的rects 因子,但要匹配type 填充中的颜色,只需将它们设置为ac

value = runif(n = 1000) 
type = rep(c("a","b","c","d"),250) 
type2 = rep(c("a","b"),500) 
number = sample(1:4, 1000, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
feature = c(rep("small",500),rep("big",500))
nFac <- 4 # define number of factors (types) here
rects <- data.frame(xmin = head(seq <- seq(0.5, nFac + .5, 1), -1), 
                  xmax = tail(seq, -1), rect_type = c("a", "c")) #set your divisions here

allResults <- data.frame(value,type,type2,number,feature, rects)

ggplot(allResults, aes(y=value, x=type)) + geom_boxplot(aes(fill = type, col=type2)) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf, fill = rect_type), alpha = 0.009) +
  ggtitle("comparison") + facet_grid(feature ~ number) +
  theme(legend.position = "bottom",axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_y_continuous(breaks =  seq(0, 1, by = 0.05),limits = c(0,1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2021-07-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    相关资源
    最近更新 更多