R语言 连接抖动点的线-多组匀光

toiithl6  于 2023-01-28  发布在  其他
关注(0)|答案(2)|浏览(187)

我试图在x轴上连接两种不同方法(* measure )测量值之间的抖动点,这些测量值通过先证者( a )相互关联,先证者可分为两个主要组,患者( pat )和对照( ctr *)。我的df如下:

set.seed(1)
df <- data.frame(a = rep(paste0("id", "_", 1:20), each = 2),
                 value = sample(1:10, 40, rep = TRUE),
                 measure = rep(c("a", "b"), 20), group = rep(c("pat", "ctr"), each = 2,10))

我试过了

library(ggplot2)
ggplot(df,aes(measure, value, fill = group)) + 
  geom_point(position = position_jitterdodge(jitter.width = 0.1, jitter.height = 0.1,
                                             dodge.width = 0.75), shape = 1) +
  geom_line(aes(group = a), position = position_dodge(0.75))

reprex package(v0.3.0)于2020年1月13日创建
我使用fill美学来分离两组抖动的点(* pat * 和 * ctr *),我意识到当我将group = a美学放入ggplot主调用时,它不会很好地分离,但似乎更好地链接到点。
我的问题:有没有一种方法可以更好地将线连接到(抖动)点,同时保持两个主要组 * ctr * 和 * pat * 的分离?
多谢了。

kadbb459

kadbb4591#

你遇到的最大问题是你只避开了group的点,但是线也被a避开了。
要保持直线与坐标轴保持原样,一种选择是手动减淡数据,这利用了因子是整数的特性,将group的一个级别向右移动,另一个级别向左移动。

df = transform(df, dmeasure = ifelse(group == "ctr", 
                                     as.numeric(measure) - .25,
                                     as.numeric(measure) + .25 ) )

然后,您可以使用measure作为x轴进行绘图,但随后使用“被回避”变量作为geom_pointgeom_line中的x轴变量。

ggplot(df, aes(x = measure, y = value) ) +
     geom_blank() +
     geom_point( aes(x = dmeasure), shape = 1 ) +
     geom_line( aes(group = a, x = dmeasure) )

如果你还想抖动,也可以手动添加到你的x和y变量。

df = transform(df, dmeasure = ifelse(group == "ctr", 
                                     jitter(as.numeric(measure) - .25, .1),
                                     jitter(as.numeric(measure) + .25, .1) ),
               jvalue = jitter(value, amount = .1) )

ggplot(df, aes(x = measure, y = jvalue) ) +
     geom_blank() +
     geom_point( aes(x = dmeasure), shape = 1 ) +
     geom_line( aes(group = a, x = dmeasure) )

yxyvkwin

yxyvkwin2#

事实证明,这是一个令人惊讶的常见问题,我想给自己加上一个答案/评论,并建议一个--我现在认为--更好的可视化:

  • 散点图 *。

我最初打算显示配对数据,并在两个比较之间直观地引导眼睛。这种可视化的问题是显而易见的:每个对象都被可视化了两次。这导致了一个相当拥挤的图形。此外,数据的两个维度(测量之前和之后)被强制为一个维度(y),ID的连接被笨拙地强制到x轴上。
散点图自然地表示ID,每个受试者只显示一个点,但在x和y上更自然地显示两个维度。唯一需要的步骤是使数据更宽(是的,这有时也是必要的,ggplot并不总是需要长数据)。

library(tidyr)
library(dplyr)
library(ggplot2)

## first reshape the data wider (one column for each measurement)
df %>% 
  pivot_wider(names_from = "measure", values_from = "value", names_prefix = "time_" ) %>%
  ## now use the new columns for your scatter plot
  ggplot() +
  geom_point(aes(time_a, time_b, color = group)) +
  ## you can add a line of equality to make it even more intuitive 
  geom_abline(intercept = 0, slope = 1, lty = 2, linewidth = .2) +
  coord_equal()

相关问题