相同的轴限制了vert / hor,固定的方面,facet中的自由缩放

时间:2017-05-11 09:28:23

标签: r ggplot2

为了比较多个医学变量的结果与范围的非常大的差异,我想创建一个如下图所示的散点图

  • 每个面板水平和垂直相同的轴

  • 固定方面,使斜率= 1线穿过角落。

-

library(ggplot2)
set.seed(11)
d = rbind(
  data.frame(what = "a", v1 = rnorm(20)+0.2, v2 = rnorm(20)),
  data.frame(what = "b", v1 = rnorm(20, 100, 10)+20, v2 = rnorm(20, 100,10)))

ggplot(d, aes(x = v1, y = v2 )) +
  geom_point() +
  geom_abline(slope = 1) +
  facet_wrap(~what, scales = "free") +
  theme(aspect.ratio = 1) +
  coord_fixed(ratio = 1) + # No effect?
  stat_ellipse()

enter image description here

我知道很难通过预先计算的限制获得此功能。 Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

2 个答案:

答案 0 :(得分:1)

如果以无形的方式绘制了x和y颠倒的所有内容,则每个构面将具有相同的x和y轴。

library(ggplot2)
set.seed(11)
d = rbind(
  data.frame(what = "a", v1 = rnorm(20)+0.2, v2 = rnorm(20)),
  data.frame(what = "b", v1 = rnorm(20, 100, 10)+20, v2 = rnorm(20, 100,10)))

ggplot(d ) +
  geom_point(aes(x = v1, y = v2 )) +
  geom_blank(aes(x = v2, y = v1 )) +
  geom_abline(slope = 1) +
  facet_wrap(~what, scales = "free") +
  stat_ellipse(aes(x = v1, y = v2 )) +
  stat_ellipse(aes(x = v2, y = v1 ), alpha=0) 

答案 1 :(得分:0)

我最终使用了Setting individual axis limits with facet_wrap and scales = "free" in ggplot2中建议的解决方案@baptiste,其中包含一个虚拟geom_blank。然而,这并不完美,因为ggplots坚持使用自己关于缩放的想法,所以这条线不会经过角落。

library(ggplot2)
set.seed(11)
d = rbind(
  data.frame(what = "a", v1 = rnorm(20) + 0.2, v2 = rnorm(20)),
  data.frame(what = "b", v1 = rnorm(20, 100, 10) + 20, v2 = rnorm(20, 100,10)))

drange = do.call(rbind, by(d, d$what, function(x) extendrange(c(x$v1, x$v2))))
dummy = data.frame(what = rownames(drange), v1 = drange[,1], v2 = drange[,2] )

ggplot(d, aes(x = v1, y = v2 )) +
  geom_point() +
  geom_abline(slope = 1) +
  theme(aspect.ratio = 1) +
  coord_fixed(ratio = 1, expand = FALSE) +
  stat_ellipse() +
  geom_blank(data = dummy) +
  facet_wrap(~what, scales = "free")

enter image description here

这里是格子的解决方案,它只是按照你的要求去做。

lattice::xyplot(v2~v1|what, data = d, aspect = 1, pch = 16,
                scales = list(relation = "free"),
                panel = function(x,y, ...){
                  lattice::panel.xyplot(x, y, ...) 
                  lattice::panel.abline(a = 0, b = 1)
                },
                prepanel = function(x, y, ...){
                  lim = c(min(x, y), max(x, y))
                  list(xlim = lim, ylim = lim)
                })

enter image description here

相关问题