当无法提供颜色美学时手动创建图例

6

试图回答这个问题时,创建所需的图形的一种方法是使用ggplot2中的geom_dotplot,如下所示:

library(ggplot2)
library(reshape2)

CTscores <- read.csv(text="initials,total,interest,slides,presentation
CU,1.6,1.7,1.5,1.6
DS,1.6,1.7,1.5,1.7
VA,1.7,1.5,1.5,2.1
MB,2.3,2.0,2.1,2.9
HS,1.2,1.3,1.4,1.0
LS,1.8,1.8,1.5,2.0")

CTscores.m = melt(CTscores, id.var="initials")

ggplot(CTscores.m, aes(x=variable, y=value)) +
  geom_dotplot(binaxis="y", stackdir="up",binwidth=0.03) +
  theme_bw()+coord_flip()

enter image description here

为了区分这些点,只需添加颜色会更方便,但是geom_dotplot对颜色敏感,无法堆叠它们:
ggplot(CTscores.m, aes(x=variable, y=value, fill=initials)) +
  geom_dotplot(binaxis="y", stackdir="up",binwidth=0.03,color=NA) +
  theme_bw()+coord_flip()

enter image description here

可以使用一个hack手动添加颜色:

gg_color_hue <- function(n) {
  hues = seq(15, 375, length=n+1)
  hcl(h=hues, l=65, c=100)[1:n]
}

cols <- rep(gg_color_hue(6),4)

ggplot(CTscores.m, aes(x=variable, y=value)) +
  geom_dotplot(binaxis="y", stackdir="up",binwidth=0.03,fill=cols,color=NA) +
  theme_bw()+coord_flip()

enter image description here

很遗憾,没有图例。另外我们不能使用 aes(fill=) 来手动添加图例,因为它会使点坍塌。有没有不使用 aes() 的方法来添加图例呢?


你可以使用与这个问题中答案相同的方法。 - Roland
@Roland,搞定了。谢谢。 - Sam Dickson
1个回答

2

通过使用 gtable 包,您可以从未能堆叠点的图例中提取图例,并使用 gridExtra 包中的 grid.arrange 将该图例添加到带有彩色和堆叠点的图中,如下所示:

p1 <- ggplot(CTscores.m, aes(x=variable, y=value)) +
  geom_dotplot(binaxis="y", stackdir="up", binwidth=0.03, fill=cols, color=NA) +
  coord_flip() +
  theme_bw()

p2 <- ggplot(CTscores.m, aes(x=variable, y=value, fill=initials)) +
  geom_dotplot(binaxis="y", stackdir="up", binwidth=0.03, color=NA) +
  coord_flip() +
  theme_bw()

library(gtable)
fill.legend <- gtable_filter(ggplot_gtable(ggplot_build(p2)), "guide-box") 
legGrob <- grobTree(fill.legend)

library(gridExtra)
grid.arrange(p1, legGrob, ncol=2, widths = c(4,1))

这将会给出:

在此输入图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接