1

我想对 geom_boxplot 做一些修改:

  1. 颠倒 Y 轴的顺序(A1 在顶部,A4 在底部)。
  2. 是否可以在图表上而不是在图表旁边绘制我的图例。

这是一个例子:

aa <- c(rep("A1",5), rep("A2",3), rep("A3",4), rep("A4",9))
aa <- as.factor(aa)
per <- runif(length(aa), min=0, max=100)
per <- trunc(per)
z <- data.frame(x=aa,y=per) 
z$ch <- NA
z[z$x %in% c("A1","A2"), "ch"] <- "string1"
z[z$x %in% c("A3"), "ch"] <- "string2"
z[z$x %in% c("A4"), "ch"] <- "string3"

z$ch <- as.factor(z$ch)

p <- ggplot(z, aes(x, y, fill = ch)) + 
geom_boxplot(size = 0.2, position = "dodge", outlier.colour = "red", outlier.shape = 16,     outlier.size = 2) + 
geom_jitter(size=1) + opts(legend.position = "right") + 
scale_colour_hue("variable") +
coord_flip()
print(p)
4

1 回答 1

2

可以通过重新排序因子 (z$x) 的级别来反转 y 轴上标签的顺序:

z$x = with(z, factor(x, rev(levels(x))))

要在图中获取图例,您可以使用该legend.position选项。诀窍是,当您将其设置为例如“顶部”或“底部”时,图例将放置在绘图之外。当使用两个数字的向量时,它将图例放置在绘图内的该位置。在代码中:

p + opts(legend.position = c(0.85,0.85), 
         legend.background = theme_rect("white"))

这导致了以下情节,我认为这是您想要的:

在此处输入图像描述

请注意添加了 legend.background 以在图例周围绘制一个填充的矩形。此外,我自己并不喜欢在情节中包含图例,因为它会掩盖数据。但这当然是由您决定的:)。

于 2011-12-12T09:35:50.087 回答