Reputation: 16089
I am using ggplot with a geom_bar
layer.
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. 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.
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). 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. (This might be solved by solving the first point.)Upvotes: 0
Views: 1040
Reputation: 23574
I ended up choosing annotate()
to achieve your goal. 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")
Upvotes: 1