how to match points in dot plot with factors in R?

Viewed 62

I want a dot plot for mydf below

mydf <-  data.frame(city=c(rep(c("Rome","NY","LA"),3)),
                           old=c(11,23,13,24,12,13.5,15,17,22),
                           new=c(12,22,13.5,25,14,15,12,17,14),
                            method=c("a","a","a","b","b","b","c","c","c"))
my_cols <- c("red", "blue", " dark green")
grps <- as.factor(mydf$method)
dotchart(mydf$old, labels = mydf$city,
         groups = grps, gcolor = my_cols,
         color = my_cols[grps],
         cex = 0.6,  pch = 19, xlab = "value")
meth1<- mydf[mydf$method=="a",]
meth2<- mydf[mydf$method=="b",]
meth3<- mydf[mydf$method=="c",]
points(meth1$new, 1:nrow(meth1), col = "orange", pch = 16, cex = 0.6)
points(meth2$new, 1:nrow(meth2), col = "light blue", pch = 16, cex = 0.6)
points(meth2$new, 1:nrow(meth2), col = "green", pch = 16, cex = 0.6)

before adding points(), I get plot below, which is what I want as a basis. enter image description here

but when I add points, all of them appear in the bottom part of the plot. I want the "new" values corresponding to each method appear in its own part of the plot and a segment line connects the old and the new values accordingly.

enter image description here how can I do that in my code? thanks for any help with this.

1 Answers

The y-axis in the dotchart, under the hood, is really just integers. So you have to provide the correct y-axis values to points():

points(meth1$new, 11:13, col = "orange", pch = 16, cex = 0.6)
points(meth2$new, 6:8, col = "light blue", pch = 16, cex = 0.6)
points(meth2$new, 1:3, col = "green", pch = 16, cex = 0.6)

I reached those values by just eyeballing the plot and counting up. Note that not all these points will appear if they are outside the range of the original dotchart call. You can adjust that by setting xlim = c(11,25) or something appropriate in the dotchart call.

Related