Reputation: 319
I want to add labels to my ggplot2 bars and change the color of the label. Somehow I can't.
My dataset is (simplified) approximatly in this format:
data$value <- runif(27, min=10, max=60)
data$A <- factor((rep(1:3, each=9)))
data$B <- factor((rep(1:9, each=3)))
data$variable <- factor(rep(rep(1:3),9))
The plot would be like:
three <- c(pink="#BD1550",dark="#490A3D",blue1="#0b6fa1",white="#FFFFFF", "#FFFFFF")
m<- data %>% group_by(A, variable) %>% summarise(mean=mean(value), sd=sd(value)) %>%
ggplot(aes(x=A,fill=variable)) +
geom_col(aes(y=mean),position="stack")+
geom_text(aes(label=round(mean,digits=2),y=mean, colour="white")
,size=3, show.legend = F, position = position_stack(vjust = 0.5))+
scale_fill_manual(values=three) + theme(legend.position="right")
Now, for the colour in geom_text I have tried:
Different solutions give different colors for each label, pink, orange, green, a blue from my string 'three', but never give me the color white. I have also tried to make it different colors than white, but somehow I have no control over what color it gives me back.
I get no error messages.
I am starting to run out of ideas. Anyone any solutions?
Upvotes: 4
Views: 6041
Reputation: 125228
The problem is that your are mapping "white" on the color aesthetic inside aes()
. This way ggplot
thinks you want to map a variable on the color aesthetic, i.e. "white" is not interpreted as the name of a color. Instead ggplot
simply picks the color from its default palette, which is "red". Simply pass the color as an argument to geom_text
outside of aes()
. Or use scale_color_manual
to set the color palette. (; Try this:
library(ggplot2)
library(dplyr)
set.seed(42)
data <- data.frame(
value = runif(27, min=10, max=60),
A = factor((rep(1:3, each=9))),
B = factor((rep(1:9, each=3))),
variable = factor(rep(rep(1:3),9))
)
three <- c(pink="#BD1550",dark="#490A3D",blue1="#0b6fa1", white="#FFFFFF", "#FFFFFF")
m <- data %>%
group_by(A, variable) %>%
summarise(mean=mean(value), sd=sd(value)) %>%
ggplot(aes(x=A, fill=variable)) +
geom_col(aes(y = mean),position="stack")+
geom_text(aes(label = round(mean, digits=2), y=mean), colour="white"
,size=3, show.legend = F, position = position_stack(vjust = 0.5))+
scale_fill_manual(values=three) + theme(legend.position="right")
m
Created on 2020-04-14 by the reprex package (v0.3.0)
Upvotes: 5