multiple colors in axes titles in ggplot

前端 未结 2 1025
借酒劲吻你
借酒劲吻你 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 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

提交回复
热议问题