当您无法提供色彩美感时,手动创建图例

Sam*_*son 5 r legend ggplot2

在试图回答这个问题,以创建所希望的描绘一个方法是使用geom_dotplot来自ggplot2如下:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

为了区分这些点,只需添加颜色,但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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但是,可以使用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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

不幸的是,没有传说.最重要的是,我们不能aes(fill=)尝试手动添加图例,因为它会折叠点.有没有办法在不使用的情况下添加图例aes()

Jaa*_*aap 2

在该包的帮助下,gtable您可以从图例中提取图例,该图例无法堆叠点,并将该图例grid.arrangegridExtra包中添加到带有彩色和堆叠点的图中,如下所示:

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))
Run Code Online (Sandbox Code Playgroud)

这使:

在此输入图像描述