Search code examples
rplotlatticedot

Change colors of x-axis labels in dotplot from Lattice package R


I was wondering if there was a way to change the color of certain x-axis labels on a dotplot that I created using the lattice package in R.

This is an example of my data/code:

State <- factor(c("AZ", "AR", "NJ"))
Value <- c(1.2, 4.5, 2.0, 1.5, 4.0, 1.4)
Year <- c(2000, 2000, 2000, 2005, 2005, 2005)

p <- dotplot(Value ~ State, groups = Year, main = "Test Data",
        xlab = "State/Territory", ylab = "Data", auto.key = TRUE)

I would like AZ and AR to be grouped together (be the same color text in the x-axis, we can make it blue)

I would like NJ to be its own group (be a different color in the x-axis text, we can make it pink)

Could I also draw a vertical line in the graph to better separate the groups?

Thank you for your help!


Solution

  • Controlling this on legacy plotting systems is extremely complicated as can be seen here. One approach might be to use a modern plotting system like ggplot2.

    library(ggplot2)
    data <- data.frame(State = factor(c("AZ", "AR", "NJ")),Value = c(1.2, 4.5, 2.0, 1.5, 4.0, 1.4), Year = c(2000, 2000, 2000, 2005, 2005, 2005))
    
    ggplot(data,aes(x=State,y=Value,color = State, shape = as.factor(Year))) + 
      geom_point(size = 3) + scale_color_manual(values=c("blue","blue","pink")) + scale_shape_discrete(name = "Year") +
      theme(axis.text.x = element_text(colour = c("blue","blue","pink")), plot.title = element_text(hjust = 0.5)) +
      geom_vline(xintercept = 2.5) + labs(title = "Test Data", x = "State/Territory", y = "Data") 
    

    Plot