customize ggplot2 axis labels with different colors

前端 未结 2 1326
心在旅途
心在旅途 2020-12-04 19:47

I have a basic bar graph I\'ve created from ggplot2. The y variable contains both positive and negative values and about half the vector of values are negative. I would like

相关标签:
2条回答
  • 2020-12-04 20:07

    I, too, get the warning message mentioned in @Mark Neal's comment; it makes me nervous. Here's an alternative approach with the ggtext package. You can wrap the categories for the x-axis in <span>s and specify the color you want, and then use element_markdown in the theme:

    library(ggtext)
    library(tidyverse)
    
    data %>%
      mutate(x.label = paste("<span style = 'color: ",
                             ifelse(y > 0, "black", "red"),
                             ";'>",
                             x,
                             "</span>", sep = ""),
             x.label = fct_reorder(x.label, as.character(x))) %>%
      ggplot(aes(x=x.label, y=y)) + 
      geom_bar(stat = "identity", aes(fill=category)) +
      theme(axis.text.x = element_markdown(angle = 45, hjust = 1))
    

    0 讨论(0)
  • 2020-12-04 20:14

    You can provide a vector of colors to the axis.text.x option of theme():

    a <- ifelse(data$category == 0, "red", "blue")
    
    ggplot(data, aes(x = x, y = y)) + 
        geom_bar(stat = "identity", aes(fill = category)) +
        theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = a))
    

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