Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get axis ticks labels with different colors within a single axis for a ggplot graph?

Tags:

r

ggplot2

Consider a simple ggplot2 graph

library(ggplot2) 
dat <- data.frame(name=c("apple", "orange", "plum"),value=c(3,8,2),outlier=c(FALSE,TRUE,FALSE))
ggplot(dat)+geom_point(aes(x=value,y=name))

enter image description here

Is there a way to modify styles attributes of the axis y labels (say color) conditionally, for example depending on the outlier column in dat?

The result would be something like

enter image description here

On a graph with a large number of items this feature wold greatly improve the graph readability and impact.

like image 884
user2147028 Avatar asked Jun 06 '14 06:06

user2147028


People also ask

How do I customize axis labels in R?

To set labels for X and Y axes in R plot, call plot() function and along with the data to be plot, pass required string values for the X and Y axes labels to the “xlab” and “ylab” parameters respectively. By default X-axis label is set to “x”, and Y-axis label is set to “y”.

How do I add axis tick marks in R?

To hide or to show tick mark labels, the following graphical parameters can be used : xaxt : a character specifying the x axis type; possible values are either “s” (for showing the axis) or “n” ( for hiding the axis)

How do I add a minor tick in ggplot2?

Adding minor ticks to graphs is very simple. There are two mains ways, using the continuous scale functions such as scale_x_continuous() or using the guides() function, both from ggplot2 . Note that guide_prism_minor() does not work with discrete axes as they do not have minor breaks.


1 Answers

A simpler way (IMO) to do this is just create a conditional color vector and parse it into axis.text.y

dat <- data.frame(name=c("apple", "orange", "plum"),value=c(3,8,2),outlier=c(FALSE,TRUE,FALSE))
colvec <- character(dim(dat)[1])
colvec <- ifelse(dat$outlier, "red", "black")

library(ggplot2) 
ggplot(dat) +
geom_point(data = dat, aes(x=value,y=name)) +
theme(axis.text.y = element_text(colour=colvec))

enter image description here

like image 162
David Arenburg Avatar answered Oct 04 '22 06:10

David Arenburg