ggplot2:qplot facet轴自由缩放,同时保留网格

时间:2014-06-22 09:22:57

标签: r plot ggplot2

我有以下情节(借鉴http://www.statmethods.net/advgraphs/ggplot2.html):

plot with facet and fixed axis

由以下代码创建:

library(ggplot2) 

# create factors with value labels 
mtcars$gear <- factor(mtcars$gear,levels=c(3,4,5),
                      labels=c("3gears","4gears","5gears")) 
mtcars$am <- factor(mtcars$am,levels=c(0,1),
                    labels=c("Automatic","Manual")) 
mtcars$cyl <- factor(mtcars$cyl,levels=c(4,6,8),
                     labels=c("4cyl","6cyl","8cyl")) 

q <- qplot(hp, mpg, data=mtcars, shape=am, color=am, size=I(3), facets=gear~cyl,
      xlab="Horsepower", ylab="Miles per Gallon")
print(q)

现在我希望轴能够更好地扩展&#34;。例如,3档齿轮轴可以缩放到10到25的范围。但是我仍然希望保留圆柱齿轮网格,我希望每列只有一个刻度。

所以以下符合我的期望:

q <- qplot(hp, mpg, data=mtcars, shape=am, color=am, size=I(3),
      xlab="Horsepower", ylab="Miles per Gallon")
q <- q + facet_wrap(facets=gear~cyl, scales="free_y")
print(q)

plot with facet and destroyed grid

有没有办法用ggplot2来实现这个目标?

1 个答案:

答案 0 :(得分:2)

如果每列或每行只需要一个比例,那么您应该使用facet_grid()代替facet_wrap(),因为facet_wrap() scales="free"的每个方面都是独立处理的以您设置的列数对齐。

qplot(hp, mpg, data=mtcars, shape=am, color=am, size=I(3),
           xlab="Horsepower", ylab="Miles per Gallon") + 
           facet_grid(facets=gear~cyl, scales="free_y")

solution