multiple colors in axes titles in ggplot

前端 未结 2 1006
借酒劲吻你
借酒劲吻你 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)
    
    0 讨论(0)
  • 2020-12-07 02:18

    Extending David Arenburg's comment, this gets a little closer without getting into the grid level:

    library(reshape2)  # easier to group by color with melted data
    
    temp <- melt(mpg[mpg$model=="a4", c("trans", "cty", "hwy")], id.vars = "trans")
    

    making label strings identified by the same variable for grouping:

    labs <- data.frame(variable = c("cty", "hwy"), 
                       value = c("MPG (city); ", "MPG (hwy) "), 
                       y = c(22,26))  # vertical position for labels
    
    
    
    p <- ggplot(temp, aes(x=trans, y=value, color=variable)) +
      geom_point() + 
      geom_text(data = labs, angle = 90, # add rotated text near y-axis
                aes(x = 0.5, y = y, label = value)) +
      scale_color_manual(values=c("red", "dark green"), guide = "none") +
      ylab("") # hide default y-axis label
    

    Who says y-axis can't be labeled on the right side, anyhow?

    2-color y-axis label

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