Sarah
Sarah

Reputation: 463

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!

Upvotes: 1

Views: 1006

Answers (3)

Pacorro
Pacorro

Reputation: 1

# This could be a solution with lattice

dotplot(Value ~ State, data, groups = State,
        scales = list(x = list(col = ifelse(levels(data$State) %in% c("AZ", "AR"), "blue", "deeppink2"))),
        par.settings = list(superpose.symbol = list(col = c("blue", "blue", "deeppink2"), pch = 16)),
        panel = function(...) {
          panel.abline(v = 2.5)
          panel.dotplot(...)
        })

Upvotes: 0

StupidWolf
StupidWolf

Reputation: 46978

Well, just for fun, sometimes lattice is not that complicated and it is still remarkably fast doing some massive plots.

In your case, you need to specify the group to be State and then use col to specify 3 colors, and do panel.abline inside the panel function, for example:

dotplot(Value ~ State, groups=State,
main = "Test Data",
col=c("blue","blue","brown"),
panel = function(x, y,...) {
         panel.dotplot(x, y,levels.fos = unique(x),...)
         panel.abline(v=2.5)
       })

enter image description here

Of course one downside is you cannot easily specify another group variable, for example year here.

Upvotes: 2

Ian Campbell
Ian Campbell

Reputation: 24878

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

Upvotes: 1

Related Questions