3

I am trying to create a Cleveland Dot Plot given for two categories in this case J and K. The problem is the elements A,B,C are in both categories so R keeps farting. I have made a simple example:

x <- c(LETTERS[1:10],LETTERS[1:3],LETTERS[11:17])
type <- c(rep("J",10),rep("K",10))
y <- rnorm(n=20,10,2)
data <- data.frame(x,y,type)
data
data$type <- as.factor(data$type)
nameorder <- data$x[order(data$type,data$y)]
data$x <- factor(data$x,levels=nameorder)

ggplot(data, aes(x=y, y=x)) +
geom_segment(aes(yend=x), xend=0, colour="grey50") +
geom_point(size=3, aes(colour=type)) +
scale_colour_brewer(palette="Set1", limits=c("J","K"), guide=FALSE) +
theme_bw() +
theme(panel.grid.major.y = element_blank()) +
facet_grid(type ~ ., scales="free_y", space="free_y") 

Ideally, I would want a dot plot for both categories(J,K) individually with each factor(vector x) decreasing with respect to the y vector. What ends up happening is that both categories aren't going from biggest to smallest and are erratic at the end instead. Please help!

MrFlick
  • 195,160
  • 17
  • 277
  • 295
theamateurdataanalyst
  • 2,794
  • 4
  • 38
  • 72
  • For future reference, question titles like "I am having trouble with ggplot2" are borderline useless. At least attempt to describe your problem. – thelatemail Jun 17 '14 at 04:43
  • @thelatemail I was just thinking that and took a stab at improving. – MrFlick Jun 17 '14 at 04:43

1 Answers1

4

Unfortunately factors can only have one set of levels. The only way i've found to do this is actually to create two separate data.frames from your data and re-level the factor in each. For example

data <- data.frame(
    x = c(LETTERS[1:10],LETTERS[1:3],LETTERS[11:17]),
    y = rnorm(n=20,10,2),
    type= c(rep("J",10),rep("K",10))
)
data$type <- as.factor(data$type)

J<-subset(data, type=="J")
J$x <- reorder(J$x, J$y, max)
K<-subset(data, type=="K")
K$x <- reorder(K$x, K$y, max)

Now we can plot them with

ggplot(mapping = aes(x=y, y=x, xend=0, yend=x)) + 
   geom_segment(data=J, colour="grey50") +
   geom_point(data=J, size=3, aes(colour=type)) +
   geom_segment(data=K, colour="grey50") +
   geom_point(data=K, size=3, aes(colour=type)) + 
   theme_bw() +
   theme(panel.grid.major.y = element_blank()) +
   facet_grid(type ~ ., scales="free_y", space="free_y") 

which results in

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295