0

I have created a chart and am wanting to colour one of the x-axis items based on a variable. I have seen this post (How to get axis ticks labels with different colors within a single axis for a ggplot graph?), but am struggling 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 tips on how to make the x-axis value red when it is equal to myvar?

Update: Thanks to @ddiez for some guidance. I finally came around to the fact that i would have to reorder prior to plotting. I also should have made my original example with data.table, so am not sure if this would influenced original responses. I modified my original dataset to be a data.table and used the following code to achieve success.

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

Community
  • 1
  • 1
Dan
  • 2,625
  • 5
  • 27
  • 42

1 Answers1

0

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

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")))

A solution using the variable myvar (yet, there may be better ways):

# 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))
ddiez
  • 1,087
  • 11
  • 26
  • 1
    While addressing this specific example, it doesn't answer the original question, which is how to do it based on a match with `myvar` where the value could be changed. – Dan Oct 29 '14 at 04:47
  • I haven't used quite your approach for the colour vectors but you gave some good guidance. I have updated my question to reflect my answer, but I am not sure if yours or mine is a cleaner/faster approach. – Dan Oct 29 '14 at 22:57
  • @Dan if you have an alternative answer maybe you can post it as a proper answer (instead inline the question), so that it can be voted. – ddiez Oct 30 '14 at 03:13