Skip to content
Prev 275547 / 398506 Next

Help with a scatter plot

Hi:

The sort of thing you appear to want is fairly straightforward to in
lattice and ggplot2, as both have ways to automate conditioning plots.
Since you were looking at ggpot2, let's consider that problem. You
don't really show enough data to provide a useful demonstration, but
let's see if we can capture the essential structure.
The first step is to melt the data so that Store becomes a factor
variable and its corresponding values are assigned to another
variable. To that end, one can invoke the very useful melt() function
in the reshape2 package:

library('reshape2')
mdata <- melt(mydata, id = c('Product', 'Color', 'Price'))

This creates a new data frame with variables Product, Color, Price,
variable and value. variable contains StoreA, ... StoreD as factor
levels and value is a numeric variable consisting of the corresponding
values. For its structure, see
str(mdata)

If you want to change StoreA - StoreD to A - D, say, then you could
optionally do

mdata$variable <- factor(mdata$variable, labels = LETTERS[1:4])


Assuming that you've done enough reading to understand what aesthetics
are about, the problem is essentially this:

x = Price
y = value
shape = Color
faceting variable = variable (the stores)

So a template of a ggplot2 graph for the melted data might look something like

library('ggplot2')
ggplot(mdata, aes(x = Price, y = value, shape = Color)) +
    geom_point() +
    facet_wrap( ~ variable, ncol = 2) +
   scale_shape_manual('Color', breaks = levels(mdata$Color),
                                             values = c(4, 0, 2, 8),
                                             labels = c('Blue',
'Green', 'Red', 'Yellow'))

This assigns  x, box, triangle and asterisk as shapes via their
numeric codes (see Hadley Wickham's ggplot2 book, p. 197 for the
reference). The labels = argument lets you change the letters B, G, R,
Y (which would comprise the default labels) to something more
evocative.

If for some odd reason you wanted to add corresponding colors to the
shapes, you could also do that, as follows:

ggplot(mdata, aes(x = Price, y = value, shape = Color, colour = Color)) +
    geom_point() +
    facet_wrap( ~ variable, ncol = 2) +
   scale_shape_manual('Color', breaks = levels(mdata$Color),
                                             values = c(4, 0, 2, 8),
                                             labels = c('Blue',
'Green', 'Red', 'Yellow')) +
   scale_colour_manual('Color', breaks = levels(mdata$Color),
                                             values = c('blue',
'green', 'red', 'yellow'),
                                             labels = c('Blue',
'Green', 'Red', 'Yellow'))

This should color the shapes in the graph and provide one (merged)
legend with colored shapes as symbols.

HTH,
Dennis
On Tue, Oct 25, 2011 at 11:48 PM, RanRL <rnrlrn at gmail.com> wrote: