如何使用ggplot2在刻面图中定义y轴断点?

use*_*771 5 plot axis r ggplot2

我必须绘制具有非常不同的范围值的数据.我正在使用ggplot2的facet设计和选项facet_grid(variable ~ ., scales = "free").但是,我想在y轴上设置断点的值,使得对于所有变量,断点都是c(0, max(variable)/2, max(variable)).我试过用scale_y_continuous,但没用.

可重复的例子:

v1 <- sample(rnorm(100, 10, 1), 30)
v2 <- sample(rnorm(100, 20, 2), 30)
v3 <- sample(rnorm(100, 50, 5), 30)
fac1 <- factor(rep(rep(c("f1", "f2", "f3"), each = 10), 3))

library(reshape2)
library(ggplot2)
df1 <- melt(data.frame(fac1, v1, v2, v3))
ggplot(df1, aes(fac1, value, group = variable)) +
  geom_point() +
  facet_grid(variable ~ ., scales = "free") +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

San*_*att 2

这将绘制三个单独的图,其中 y 间隔设置为 0、0.5*max(value) 和 max(value)。使用 gtable rbind 函数将这三个图组合起来,然后绘制。

v1 <- sample(rnorm(100, 10, 1), 30)
v2 <- sample(rnorm(100, 20, 2), 30)
v3 <- sample(rnorm(100, 50, 5), 30)
fac1 <- factor(rep(rep(c("f1", "f2", "f3"), each = 10), 3))

library(reshape2)
library(ggplot2)
library(grid)
library(gridExtra)

df1 <- melt(data.frame(fac1, v1, v2, v3))

# Draw the three charts, each with a facet strip.
# But drop off the bottom margin material
dfp1 = subset(df1, variable == "v1")
p1 = ggplot(dfp1, aes(fac1, value, group = variable)) +
  geom_point() +
  facet_grid(variable ~ .) +
  scale_y_continuous(limits = c(0, ceiling(max(dfp1$value))),
      breaks = c(0, ceiling(max(dfp1$value))/2, ceiling(max(dfp1$value)))) +
  theme_bw()
g1 = ggplotGrob(p1)
pos = g1$layout[grepl("xlab-b|axis-b", g1$layout$name), "t"]
g1 = g1[-pos, ]

# Drop off the bottom margin material
dfp2 = subset(df1, variable == "v2")
p2 = ggplot(dfp2, aes(fac1, value, group = variable)) +
  geom_point() +
  facet_grid(variable ~ .) +
  scale_y_continuous(limits = c(0, ceiling(max(dfp2$value))), 
     breaks = c(0, ceiling(max(dfp2$value))/2, ceiling(max(dfp2$value)))) +
  theme_bw()
g2 = ggplotGrob(p2)
g2 = g2[-pos,]

dfp3 = subset(df1, variable == "v3")
p3 = ggplot(dfp3, aes(fac1, value, group = variable)) +
  geom_point() +
  facet_grid(variable ~ .) +
  scale_y_continuous(limits = c(0, ceiling(max(dfp3$value))), 
     breaks = c(0, ceiling(max(dfp3$value))/2, ceiling(max(dfp3$value)))) +
  theme_bw()
g3 = ggplotGrob(p3)

# Combine the three gtables
g = rbind.gtable(g1, g2, size = "max") 
g = rbind.gtable(g, g3, size = "max")

# Draw the plot
grid.newpage()
grid.draw(g)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述