问题
我希望将图例放在图的上方。我还希望将图例键符号(彩色正方形)放在图例键标签(图例文本)上方。但是,当我这样做时,图例键符号会“拉伸”以适应标签的大小。我想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
),我已经尝试了以下内容以及其他内容:
从这里和这里:
p + guides(colour = guide_legend(override.aes = list(size=3)))
从这里:
p + guides(colour = guide_legend(keywidth = .5, keyheight = .5))
和p + guides(colour = guide_legend(keywidth = unit(.5, "cm"), keyheight = unit(.5, "cm")))
从这里:(尝试包装标签)
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)))
。你有一个填充比例尺,而不是颜色比例尺。 - Marius