Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

r - How to get axis ticks labels with different colors within a single axis for a ggplot graph?

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

enter image description here

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

enter image description here

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...