How to get axis ticks labels with different colors

2020-02-04 06:17发布

问题:

Consider a simple ggplot2 graph

library(ggplot2) 
dat <- data.frame(name=c("apple", "orange", "plum"),value=c(3,8,2),outlier=c(FALSE,TRUE,FALSE))
ggplot(dat)+geom_point(aes(x=value,y=name))

Is there a way to modify styles attributes of the axis y labels (say color) conditionally, for example depending on the outlier column in dat?

The result would be something like

On a graph with a large number of items this feature wold greatly improve the graph readability and impact.

回答1:

A simpler way (IMO) to do this is just create a conditional color vector and parse it into axis.text.y

dat <- data.frame(name=c("apple", "orange", "plum"),value=c(3,8,2),outlier=c(FALSE,TRUE,FALSE))
colvec <- character(dim(dat)[1])
colvec <- ifelse(dat$outlier, "red", "black")

library(ggplot2) 
ggplot(dat) +
geom_point(data = dat, aes(x=value,y=name)) +
theme(axis.text.y = element_text(colour=colvec))



回答2:

I don't think this is as good as colouring the outlier point itself, but you can hack away at the grob:

p <- ggplot(dat)+geom_point(aes(x=value,y=name))
g <- ggplotGrob(p)

#I found this by using str(g) and looking for "axis.text.y.text"
#there is probably a clever way of automating this
g[[1]][[2]]$children$axis$grobs[[1]]$gp$col <- c("grey50", "red", "grey50")

plot(g)

Doing this conditionally is possible using something like c("grey50", "red")[dat$outlier] assuming the row order is as needed. However, I can only reiterate that you probably should create a different graph if you think you need something like this.



标签: r ggplot2