Home > Blockchain >  R ggplot, reorder function mess color code of labels when confronted to same value
R ggplot, reorder function mess color code of labels when confronted to same value

Time:10-06

I have a problem with ggplot and colored labels

#example data:

names<-c("a","albert","aline","d","francis")
value<-c(11,10,9,9,21)
c<-c("black","red","red","black","red")

df<-data.frame(names,value,color)

I am trying to make a really simple barplot, with colored labels (here for the example labels that have firstname). It did this:

p<-ggplot(data=df, aes(x=reorder(names,value), y=value))  
  geom_bar(stat="identity")
p  coord_flip() 
  theme(axis.text.y = element_text(hjust = 1,colour =  reorder(c, value) ))

plot

The "d" gets the red colot and not "aline". It looke like that, when confronted to same value, the reorder function sort the names by inversed alphabetical order. However, when ordering the colors, it looks like the function doesn't work the same, as it doesnt color the right label.

I think that way because if you change "aline" with "eric" (change the alphabetical order with "d") it works the correct way.

names<-c("a","albert","eric","d","francis")
value<-c(11,10,9,9,21)
c<-c("black","red","red","black","red")

df<-data.frame(names,value,color)
p<-ggplot(data=df, aes(x=reorder(names,value), y=value))  
  geom_bar(stat="identity")
p  coord_flip() 
  theme(axis.text.y = element_text(hjust = 1,colour =  reorder(c, value) ))

I hope this is clear, if somebody has an idea on how to fix this, you are more than welcomed

CodePudding user response:

Following @MonJeanJean's advice, I took the liberty to rename a few objects.

names <- c("a", "albert", "aline", "d", "francis")
value <- c(11, 10, 9, 9, 21)
colvec <- c("black", "red", "red", "black", "red")

dat <- data.frame(names, value, colvec)

The problem comes from the function reorder: applied on the colors, it would work only if there was one color per bar. The following will work on your example:

ggplot(data = dat, aes(x = reorder(names, value), y = value, fill = I(colvec)))  
  geom_col()   
  coord_flip()  
  theme(axis.text.y = element_text(colour = colvec[order(value)]))

CodePudding user response:

Changing the colours of labels through vectorised input to theme elements is not really supported. Instead, one can use the ggtext package to markup text with (some) html tags.

library(ggplot2)
library(ggtext)

names<-c("a","albert","aline","d","francis")
value<-c(11,10,9,9,21)
color<-c("black","red","red","black","red")

df<-data.frame(names,value,color)
df$xlabel <- glue::glue("<span style='color:{color}'>{names}</span>")

ggplot(data=df, aes(x=reorder(xlabel,value), y=value))  
  geom_bar(stat="identity")  
  theme(axis.text.x = element_markdown())

Created on 2021-10-05 by the reprex package (v0.3.0)

  • Related