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

后端 未结 2 1734
粉色の甜心
粉色の甜心 2020-12-09 05:28

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


        
相关标签:
2条回答
  • 2020-12-09 05:35

    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

    0 讨论(0)
  • 2020-12-09 05:50

    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)
    

    enter image description here

    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.

    0 讨论(0)
提交回复
热议问题