繁体   English   中英

"ggplot2:在非正交(例如,-45 度)轴上投影点或分布"

[英]ggplot2: Projecting points or distribution on a non-orthogonal (eg, -45 degree) axis

下图是 Michael Clark 使用的概念图, https:\/\/m-clark.github.io\/docs\/lord\/index.html<\/a>用于解释 Lord 悖论以及回归中的相关现象。

我的问题是在这种情况下提出的,并使用ggplot2<\/code>但在几何和图形方面更广泛。

我想重现这样的数字,但使用实际数据。 我需要知道:

有趣的问题! 我还没有遇到它,但可能有一个包可以帮助自动执行此操作。 这是使用两个技巧的手动方法:

  1. coord_*函数的“clip”参数,允许我们在绘图区域之外添加注释。
  2. 构建密度图,提取其坐标,然后旋转和平移这些坐标。

首先,我们可以绘制从初始到最终变化的密度图,看到左偏分布:

(my_hist <- df %>%
  mutate(y_min_x = final - initial) %>%
  ggplot(aes(y_min_x)) +
  geom_density())

在此处输入图像描述

现在我们可以提取该图的内容,并将坐标转换为我们希望它们出现在组合图中的位置:

a <- ggplot_build(my_hist)
rot = pi * 3/4
diag_hist <- tibble(
  x = a[["data"]][[1]][["x"]],
  y = a[["data"]][[1]][["y"]]
) %>%
  # squish
  mutate(y = y*0.2) %>%
  # rotate 135 deg CCW
  mutate(xy = x*cos(rot) - y*sin(rot),
         dens = x*sin(rot) + y*cos(rot)) %>%
  # slide
  mutate(xy = xy - 0.7,  #  magic number based on plot range below
         dens = dens - 0.7)

这是与原始情节的组合:

ggplot(df, aes(x = initial, y = final, color = group)) +
  geom_point() + 
  geom_smooth(method = "lm", formula  =  y~x) +
  stat_ellipse(size = 1.2) +
  geom_abline(slope  =  1, color = "black", size = 1.2) +
  coord_fixed(clip = "off", 
              xlim = c(-0.7,1.6),
              ylim = c(-0.7,1.6), 
              expand = expansion(0)) +
  annotate("segment", x = -1.4, xend = 0, y = 0, yend = -1.4) +
  annotate("path", x = diag_hist$xy, y = diag_hist$dens) +
  theme_bw() +
  theme(legend.position = c(.15, .85), 
        plot.margin = unit(c(.1,.1,2,2), "cm")) 

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM