multiple colors in axes titles in ggplot

前端 未结 2 1024
借酒劲吻你
借酒劲吻你 2020-12-07 01:37

How can I have multiple colors for an axes label in ggplot?

As an example, instead of a legend, I would like the y-axis label to be red and green to correspond to th

2条回答
  •  青春惊慌失措
    2020-12-07 01:53

    I don't think you should abuse an axis title as a legend, but you can do this at the grid level:

    library(ggplot2)
    
    p <- ggplot(mpg[mpg$model=="a4",],aes(x=trans,y=cty))+
      geom_point(color="red")+
      geom_point(aes(y=hwy),color="dark green") +
      ylab("MPG (city); MPG (hwy)")
    
    g <- ggplotGrob(p)
    
    g[[1]][[7]]$label <- c("MPG (city);",  "MPG (hwy)")
    g[[1]][[7]]$gp$col <- c("red", "dark green")
    library(grid)
    g[[1]][[7]]$y <- unit(c(0.45, 0.54), "npc")
    #fiddle with the coordinates until the positioning fits for your specific strings
    
    plot(g)
    

    enter image description here

    Of course it would be preferable to simply create a legend by using proper mapping of the color variable.

    Update

    With ggplot2 v2.2.1 this needs to be adjusted since the gtree has changed. Now this works:

    #g[[1]] shows which grob is the y axis title
    #then use str to see the structure of the grop
    #you can also use grid.edit instead but I find the following more easy
    g[[1]][[13]]$children[[1]]$label <- c("MPG (city);",  "MPG (hwy)")
    g[[1]][[13]]$children[[1]]$gp$col <- c("red", "dark green")
    g[[1]][[13]]$children[[1]]$hjust <- c(1, 0)
    g[[1]][[13]]$children[[1]]$y <- unit(c(0.5, 0.5), "npc")
    
    plot(g)
    

提交回复
热议问题