Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

customize ggplot2 axis labels with different colors

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 to customize the axis labels such that when the y value of that corresponding x factor is a negative, its label is red. Here's a reproducible example:

#Create data x <- c("a","b","c","d","e","f") y <- c("10", "9","-10","11","-3","-15") data <- data.frame(x, y) data$y <- as.numeric(as.character(data$y))  data$category <- ifelse(as.numeric(data$y)<0, 0, 1) data$category <- as.factor(data$category)  #Graph library(cowplot) #theme library(ggplot2)  ggplot(data, aes(x=x, y=y)) +    geom_bar(stat = "identity", aes(fill=category)) +   theme(axis.text.x = element_text(angle = 45, hjust = 1)) +   theme(axis.text.x = element_text(colour = "black")) 

enter image description here

What I need is a way to change the label colors of "c", "e", and "f" to the color of my choosing. I tried toggling theme(aes(axis.text.x=element_text(colour=Air_pricier))) but that produced an error. Thanks in advance.

like image 571
Cyrus Mohammadian Avatar asked Aug 10 '16 00:08

Cyrus Mohammadian


2 Answers

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

enter image description here

like image 151
Sumedh Avatar answered Sep 24 '22 02:09

Sumedh


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

enter image description here

like image 26
A. S. K. Avatar answered Sep 20 '22 02:09

A. S. K.