0

I am replicating a version of this dotplot http://blogs.bgsu.edu/math6820cwenren/files/2011/04/ggplot-dotplot.png from http://blogs.bgsu.edu/math6820cwenren/2011/04/27/ggplot2/. Code is below.

I would like the plot and the key to match in the order of presentation. This could be accomplished by reordering the variable ind to appear as in the plot, i.e., Tracy, LeBron, Kobe, Anthony. Or vice-versa and reorder the key. I've tried reordering the factors with several methods but the order in key is always reverse the order in the plot.

How to reorder so the presentation is consistent?

Kobe=c(31.6, 28.3, 26.8, 27.0, 24.8)
LeBron=c(27.3, 30.0, 28.4, 29.7, 26.0)
Tracy=c(24.6, 21.6, 15.6, 8.6, 8.5)
Anthony=c(28.9, 25.7, 22.8, 28.2, 25.3)
year=c(2006, 2007, 2008, 2009, 2010)

data1=cbind(Kobe, LeBron, Tracy, Anthony)

data=data.frame(data1,row.names=year)

d=data.frame(Year=dimnames(data)[[1]],stack(data))

p=ggplot(d, aes(values, ind, color=ind))
p + geom_point()+ facet_wrap(~Year, ncol=1)
bdemarest
  • 14,397
  • 3
  • 53
  • 56
David
  • 3
  • 1
  • 4

1 Answers1

1

You can order the levels with factor and a character vector specifying the order of levels:

d$ind <- factor(d$ind, levels = unique(d$ind))

Here, unique(d$ind) returns the values in the order of appearance in the data frame. This is the order of levels for the color scale.

You want a reversed order of levels for the y axis. By default, the order is bottom to top. You can create a second variable, ind2, with reversed level order:

d$ind2 <- factor(d$ind, levels = rev(levels(d$ind)))

This will be used as the variable for the y axis.

library(ggplot2)
ggplot(d, aes(x = values, y = ind2, color = ind)) +
  geom_point() + facet_wrap(~ Year, ncol = 1)

enter image description here

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • This does not answer the question. Anthony now listed first on y axis while Kobe listed first in key on the right. My question: how to reorder so that Anthony first on y axis and first in the key? – David Dec 16 '13 at 23:24