[英]ggplot2 Use text colour as a legend for fill
I am using ggplot with a geom_bar
layer. 我正在使用带有geom_bar
层的geom_bar
。
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)
I would like to reproduce factor annotations I have seen that is different to ggplot
default guides. 我想重现与ggplot
默认指南不同的因子注释。 Instead of the fill
aesthetic being in a legend to the right of the panel with text alongside each fill colour, I would like the text to be coloured and present in the panel. 我不希望fill
美学出现在面板右侧的图例中,在每种填充颜色旁边显示文本,我希望将文本着色并显示在面板中。
This is the default option: 这是默认选项:
ggplot(filter(dat.m, variable != "Other")) +
geom_bar(aes(x = variable, y = value, fill=FF),
stat="identity")
This is what I have done to mimic the style I am after: 这是我模仿我追求的风格所做的:
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)
Some problems: 一些问题:
max
of the stacks, which is fine if the bars are of a similar height). (这里是堆栈的max
,如果这些条的高度相似,这很好。) Can the text be in the top right of the chart background? 文字可以在图表背景的右上方吗? hjust=0
makes it left-aligned, but with the left margin of the text to the middle of the category. 使用hjust=0
使其左对齐,但文本的左边缘位于类别的中间。 (This might be solved by solving the first point.) (这可以通过解决第一点来解决。) I ended up choosing annotate()
to achieve your goal. 我最终选择了annotate()
来实现您的目标。 You can specify the colours for texts in this way. 您可以通过这种方式指定文本的颜色。
ggplot(data = filter(dat.m, variable != "Other"),
aes(x = variable, y = value, fill = FF)) +
geom_bar(stat="identity") +
annotate("text", x = 2.55, y = 2.6, label = "F1", color = "#F8766D") +
annotate("text", x = 2.55, y = 2.7, label = "F2", color = "#00BA38") +
annotate("text", x = 2.55, y = 2.8, label = "F3", color = "#619CFF") +
theme(legend.position="none")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.