GGPLOT facet_grid:如何对值组合绘图进行排序

时间:2013-09-05 14:52:21

标签: r ggplot2

编辑: 这不是常见问题解答,我不打算在facet_grid中订购一个图但是两个。 像d $ x< - reorder(d $ x,d $ y,mean)之类的东西只会重新排序下方面上的绘图而不是另一面上的绘图... 我希望根据点图中的值重新排序这两个图,顶部的值。 按照常见问题解答中的建议p< - ggplot(data = d,mapping = aes(x = reorder(x,y,mean),y = y))+ ... 仅订购较低的情节 ...

所以我需要根据数据帧d2中的值对facet中的两个图上的x轴重新排序。结合这两者似乎打破了d1和d2的重新排序。


我使用以下代码组合了一个图:

library(plyr)
library(ggplot2)
library(grid)
library(gridExtra)

set.seed(123)
x <- sample( LETTERS[1:9], 10000, replace=TRUE, prob=c(0.1, 0.2, 0.15, 0.05,0.1, 0.2, 0.05, 0.05,0.1) )
y <- sample( c("Y","N"), 10000, replace=TRUE, prob=c(0.2, 0.8))
df <- as.data.frame(cbind(x,y))
names(df) <- c("x","y")
df$p_y <- as.numeric(df$y)-1

# create volume data for bar plot
d1 <- as.data.frame(table(df$x))
names(d1) <- c("x","y")
# create p(target) data for point plot
d2 <- ddply(df,1,summarise,y=mean(p_y))

d1$panel <- "volume"
d2$panel <- "p(target)"

# combine dataframes to one
d <- rbind(d1, d2)
# combine plots
p <- ggplot(data = d, mapping = aes_string(x="x", y="y")) + 
  facet_grid(panel ~ ., scales = "free") +
  theme_bw() + 
  theme(axis.text.x = element_text(angle = 90,hjust = 1)) +
  layer(data = d1, geom = c( "bar"), stat = "identity") +
  layer(data = d2, geom = c( "point"), stat = "identity")
p

这会生成一个根据x轴上的因子排序的图,默认情况下是按字母顺序...我想在第一个图中的p_target值上对X轴进行排序... 这样P(目标)从左到右递减。我一直在考虑将数据帧d排序到正确的顺序,但是facet grid puts正好按字母顺序排列......

雨果

0 个答案:

没有答案