Color single ggplot axis element

I created a chart and want to label one of the x-axis items based on a variable. I've seen this post ( How to get axis tick labels with different colors within the same axis for a ggplot? ) But I'm trying to apply it to my dataset. enter image description here

df1 <- data.frame(var=c("a","b","c","a","b","c","a","b","c"), 
                  val=c(99,120,79,22,43,53,12,27,31),
                  type=c("alpha","alpha","alpha","bravo","bravo","bravo","charlie","charlie","charlie"))

myvar="a"

ggplot(df1,aes(x=reorder(var,-val), y=val,fill=type)) + geom_bar(stat="identity")

      

Any hints on how to make the x-axis value red if it's equal myvar

?

Update: Thanks to @ddiez for some guidance. I finally came to the point where I would have to reorder before the conspiracy. I also had to do my original example with data.table, so not sure if this will affect the original answers. I changed my original dataset to be a dataset and used the following code to succeed.

df1 <- data.table(var=c("a","b","c","a","b","c","a","b","c"), 
                  val=c(99,120,79,22,43,53,12,27,31),
                  type=c("alpha","alpha","alpha","bravo","bravo","bravo","charlie","charlie","charlie"))

myvar="a"

df1[,axisColour := ifelse(var==myvar,"red","black")]
df1$var <- reorder(df1$var,-df1$val,sum)

setkey(df1,var,type)

ggplot(df1,aes(x=var, y=val,fill=type)) + geom_bar(stat="identity") +
  theme(axis.text.x = element_text(colour=df1[,axisColour[1],by=var][,V1]))

      

enter image description here

0


source to share


1 answer


There might be a more elegant solution, but a quick hack (requires you to know the final order):

ggplot(df1,aes(x=reorder(var,-val), y=val,fill=type)) +
geom_bar(stat="identity") +
theme(axis.text.x = element_text(colour=c("black","black","red")))

      



Solution using a variable myvar

(there may be better ways, though):

# reorder the factors in the data.frame (instead of in situ).
df1$var=reorder(df1$var, -df1$val)

# create a vector of colors for each level.
mycol=rep("black", nlevels(df1$var))
names(mycol)=levels(df1$var)

# assign the desired ones a different color.
mycol[myvar]="red"

ggplot(df1,aes(x=var, y=val,fill=type)) +
  geom_bar(stat="identity") +
  theme(axis.text.x = element_text(colour=mycol))

      

0


source







All Articles