ggplot:对于覆盖相同分组的2个geom,改变hue的方式不同

时间:2014-04-07 20:02:01

标签: r ggplot2

此问题来自另一个问题:Different coloring of groups in R plot

我想改变一个geom的色调而不影响另一个geom。所以这里的boxplot分组和点分组映射到同一个变量。更改一个的色调会改变另一个。如何更改框填充的色调,而不是点填充;换句话说,使点填充颜色更浅,以便它们与盒子填充的颜色相同?

#DATA

library(RColorBrewer) 
library(reshape2)

a=rnorm(100, mean=1)
b=rnorm(100, mean=0, sd=1)
ab=data.frame(a,b)
melt=melt(ab)
bpColor=brewer.pal(4, 'RdBu')

#Current

ggplot(melt, aes(fill=variable, x=variable, y=value)) +
    geom_boxplot(notch = TRUE) + 
    geom_jitter(position = position_jitter(width = .05, height =0), shape=21, size=1.5) +
    scale_fill_hue(l=40) 

enter image description here

1 个答案:

答案 0 :(得分:1)

创建一个箱形图,然后创建一个颜色较浅的点图可能更简单,并将这些点覆盖在方框上。借用this post中的想法,让我说明一下:

library(ggplot2)
library(RColorBrewer) 
library(reshape2)
library(gridExtra)
library(gtable)

# make up data
a=rnorm(100, mean=1)
b=rnorm(100, mean=0, sd=1)
ab=data.frame(a,b)
melt=melt(ab)
bpColor=brewer.pal(4, 'RdBu')

## create a boxplot
g1 <- ggplot(melt, aes(fill=variable, x=variable, y=value)) +
  geom_boxplot(notch = TRUE) + 
  scale_fill_hue(l=40) +
  theme_bw()

## create a pointplot with a lighter hue
g2 <- ggplot(melt, aes(fill=variable, x=variable, y=value)) +
  geom_jitter(position = position_jitter(width = .05, height =0), shape=21, size=3) +
  scale_fill_hue(l=100) +
  theme(panel.background = element_rect(fill = NA))

gt_boxes <- ggplot_gtable(ggplot_build(g1))
gt_points <- ggplot_gtable(ggplot_build(g2))

## overlay the points over the boxes
just_boxes <- c(subset(gt_boxes$layout, name == "panel", se = t:r))
g_together <- gtable_add_grob(gt_boxes, gt_points$grobs[[which(gt_points$layout$name == "panel")]], 
                              just_boxes$t, just_boxes$l, just_boxes$b, just_boxes$l)
grid.draw(g_together)

enter image description here