1

Let's say we observed two species of beetles. We want to compare their size using geom_violin() as done below:

df = data.frame(species=rep(c('species_a','species_b'),3), size=c(1,1.5,1.2,1.8,1.1,1.9))
ggplot(df, aes(x=species, y=size)) + geom_violin()

Knowing that the expected size range is [0.8,1.8] for species_a and [1.2, 1.8] for species_b...

ranges = list(species_a=c(0.8,1.8), species_b=c(1.2,1.8))

How can we easily add this range (with a grey shape for example) on the graph?

4

2 回答 2

4

将范围放在具有物种名称和最小/最大值的单独数据框中

ranges = data.frame(species=c('species_a','species_b'), 
                    rmin=c(0.8,1.2),rmax=c(1.2,1.8))
ranges

    species rmin rmax
1 species_a  0.8  1.8
2 species_b  1.2  1.8

然后使用新的数据框geom_rect()来制作放置在geom_violin(). geom_blank()用于根据原始数据框制作 x 轴。

ggplot(df, aes(x=species, y=size))  + geom_blank() + 
  geom_rect(data=ranges,aes(xmin=as.numeric(species)-0.45,
                            xmax=as.numeric(species)+0.45,
                            ymin=rmin,ymax=rmax),inherit.aes=FALSE)+
  geom_violin()

在此处输入图像描述

于 2013-11-13T16:33:07.623 回答
0

你可以试试这个:

# first, create data frame from list 'ranges'
df2 <- setNames(object = do.call(rbind.data.frame, ranges), nm = c("min_size", "max_size"))
df2$species <- rownames(df2)

# plot violins with 'df', and ranges with 'df2'.
# Set colour and size according to your own "data-ink ratio" preferences.
ggplot(data = df, aes(x = species)) +
  geom_violin(aes(y = size)) +
  geom_linerange(data = df2, aes(ymax = max_size, ymin = min_size), colour = "grey", size = 3)

在此处输入图像描述

于 2013-11-13T16:41:37.997 回答