gpt4 book ai didi

r - 当您无法提供颜色美感时手动创建图例

转载 作者:行者123 更新时间:2023-12-04 19:50:20 27 4
gpt4 key购买 nike

试图回答 this question ,创建所需绘图的一种方法是使用 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()

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() 的情况下添加图例? ?

最佳答案

gtable的帮助下包中,您可以使用无法堆叠点的图例从图中提取图例,并使用 grid.arrange 添加该图例来自 gridExtra打包到带有彩色 ans 堆叠点的绘图,如下所示:

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))

这使:

enter image description here

关于r - 当您无法提供颜色美感时手动创建图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34070448/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com