This is a follow up post here.

I am trying to create a faceted plot with subset data as per the code as below. In summary, out of my table I would like to plot the Price of product P3 vs the price of Product P1 and facet the plot versus version and color.

The faceting is somehow not working with the below code, instead, all the datapoints are just duplicated in every facet. Any idea on how to fix this ? And get the “desired plot” I’m attaching below (a manually hacked one)?

library(ggplot2)
product=c("p1","p1","p1","p1","p1","p1","p1","p1","p2","p2","p2","p2","p2","p2","p2","p2","p3","p3","p3","p3","p3","p3","p3","p3","p4","p4","p4","p4","p4","p4","p4","p4")
skew=c("b","b","b","b","a","a","a","a","b","b","b","b","a","a","a","a","b","b","b","b","a","a","a","a","b","b","b","b","a","a","a","a")
version=c(0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2)
color=c("C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2")
price=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32)
df = data.frame(product, skew, version, color, price)
# First plot all the data
p1 <- ggplot(df, aes(x=price, y=price, colour=factor(skew))) + geom_point(size=2, shape=19)
p1 <- p1 + facet_grid(version ~ color, labeller = label_both, , scales="free")
p1 
# Second, plot P3 prices vs P1 prices
p2 <- ggplot(df, aes(x=price[product=='p1'], y=price[product=='p3'], colour=factor(skew[product == 'p1']))) + geom_point(size=2, shape=19)
p2 <- p2 + facet_grid(version ~ color, labeller = label_both, , scales="free")
p2

The Desired plot shoud have been:

Desired plot

Instead, this is what I get This is what I get

有帮助吗?

解决方案

It happens because, as I said in your last question, you shouldn't be relying on subsetting the variables inside of aes(). You should instead be doing this:

library(reshape2)
df1 <- dcast(df,skew+version+color~product,
             fun.aggregate = sum,
             value.var = "price")
ggplot(df1,aes(x = p1,y = p3,colour = factor(skew))) +
  facet_grid(version~color) +
  geom_point(size = 2,shape = 19)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top