【发布时间】:2019-03-29 11:04:46
【问题描述】:
问题
我想将我的情节图例放在情节之上。我还想将图例键符号(彩色方块)放在图例键标签(图例文本)上方。不幸的是,当我这样做时,图例键符号“伸展”以适应标签的大小。我想 ggplot2 工作正常,但我怎么能手动覆盖这个功能呢?
如何在顶部使用可变长度的标签保持一致的图例键符号?
可重现的示例
(这不一定是一个最小的例子,以防我的实际代码的结构,如 coord_flip 和 fill 调用,有影响)
library(dplyr)
library(ggplot2)
dataFrame <- diamonds %>%
group_by(color, cut) %>%
summarise(count = n()) %>%
group_by(color) %>%
mutate(percent = count/sum(count),
pretty_label = paste0(round(percent*100, 1), "%")) %>%
ungroup()
p <- ggplot(data = dataFrame, mapping = aes(x=color, y = percent, group = cut))+
geom_bar(aes(fill = cut), stat = "identity", position = "fill")+
geom_text(aes(label = pretty_label), position=position_fill(vjust=0.5), colour="white", stat = "identity")+
coord_flip()+
theme(legend.position="top")+
guides(fill = guide_legend(label.position = "bottom", reverse = TRUE))
plot(p)
注意每个图例符号的大小不同,具体取决于标签的长度。
我已经尝试过的
我想这与指南有关,但我似乎无法正确理解。使用上面的图(p),我尝试了以下以及更多:
来自here 和here:
p + guides(colour = guide_legend(override.aes = list(size=3)))来自here:
p + guides(colour = guide_legend(keywidth = .5, keyheight = .5))和p + guides(colour = guide_legend(keywidth = unit(.5, "cm"), keyheight = unit(.5, "cm")))来自here:(尝试包装标签)
p + guides(color = guide_legend(nrow = 2))
我尝试过其他不那么“合乎逻辑”的尝试,只是因为。这些都不起作用。
最后的想法
我可能只是很难知道要搜索什么。如果你能指出我正确的方向,我总是愿意自己解决问题。任何其他资源都非常受欢迎。
谢谢,提前!
会话输出
> sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] bindrcpp_0.2.2 ggplot2_3.0.0 dplyr_0.7.6
loaded via a namespace (and not attached):
[1] Rcpp_0.12.18 bindr_0.1.1 magrittr_1.5 tidyselect_0.2.4 munsell_0.5.0 colorspace_1.3-2 viridisLite_0.3.0
[8] R6_2.2.2 rlang_0.2.1 plyr_1.8.4 tools_3.5.1 grid_3.5.1 gtable_0.2.0 withr_2.1.2
[15] yaml_2.1.19 lazyeval_0.2.1 assertthat_0.2.0 digest_0.6.17 tibble_1.4.2 purrr_0.2.5 glue_1.2.0
[22] labeling_0.3 compiler_3.5.1 pillar_1.2.3 scales_0.5.0 pkgconfig_2.0.1
【问题讨论】:
-
如果将
colour替换为fill,则“我已经尝试过的内容”下的所有选项都可以在某种程度上起作用,例如p + guides(fill = guide_legend(override.aes = list(size=3)))。你有一个填充比例,而不是一个颜色比例。 -
我认为可能也是这样。我在我的实际数据上进行了尝试,但是我的标签太长了,而且我没有将大小增加得足够多。如果尺寸小于最长的标签,则不会产生影响(至少对我而言)。我忽略了在我给出的例子中尝试这些可能性,但这可能会引导我走向正确的方向。谢谢!