我正在使用带有 geom_bar
图层的ggplot .
library(ggplot2)
library(dplyr)
library(reshape2)
dat <- data.frame(
A = c(1, 1, 0.5),
B = c(1.2, 1, 0.6),
FF = c("F1", "F2", "F3")
) %>%
mutate(Other = max(A,B))
dat.m <- melt(dat)
我想重现我看到的与 ggplot
默认指南不同的因子注释 . 我希望文本在面板中显示颜色并显示在面板右侧的图例中,而不是 fill
美审在面板右侧的图例中 .
这是默认选项:
ggplot(filter(dat.m, variable != "Other")) +
geom_bar(aes(x = variable, y = value, fill=FF),
stat="identity")
这就是我模仿我追求的风格所做的:
ggplot() +
geom_bar(filter(dat.m, variable != "Other"),
mapping = aes(x = variable, y = value, fill = FF),
stat="identity") +
geom_text(filter(dat.m, variable == "Other"),
mapping = aes(x = variable, y = value, col = FF, label=FF),
position="stack", fontface="bold") +
guides(fill = FALSE, colour=FALSE, text=FALSE)
一些问题:
-
图例位置是硬编码的 . (这里是堆栈的
max
,如果条形高度相似则没问题) . 文本可以位于图表背景的右上角吗? -
文本居中对齐 . 使用
hjust=0
使其左对齐,但文本的左边距位于类别的中间 . (这可以通过解决第一点来解决 . ) -
额外奖励:如果类别文本标签很长,可以将换行符编程为"nicely"吗?
1 回答
我最终选择
annotate()
来实现你的目标 . 您可以通过这种方式指定文本的颜色 .