如何在不使用r中的ggpair的情况下连接观测值(使用ggplot:geom_bar,geom_dotplot)

问题描述 投票:2回答:1

我使用geom_bar创建了条形图,其中x轴为“组”(女性,男性),y轴为“值”。分组进一步细分为“会话”,以便男性和女性都有“会话1”和“会话2”(即,总共四个小节)。

由于所有参与者都参加了会议1和2,因此我在四个条形图的每个条形图上覆盖了一个圆点图(geom_dot),以表示各个数据。

我现在正在尝试在会话1和2之间连接所有参与者的观测值(“ PID”)。换句话说,应该在x-的“男性”部分上连接几组两点的线。轴(即每个参与者)和“女性部分”。

我尝试使用“ geom_line”(如下),但无济于事(相反,它在“男性”中间创建了一条垂直线,在“女性”中间创建了一条垂直线)。我不太确定如何解决此问题。

请参见下面的代码:

ggplot(data_foo, aes(x=factor(Group),y=Values, colour = factor(Session), fill = factor(Session))) + 
          geom_bar(stat = "summary", fun.y = "mean", position = "dodge") + 
          geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 1.0, position = "dodge", fill = "black") +
          geom_line(aes(group = PID), colour="dark grey") +
          labs(title='My Data',x='Group',y='Values') +
          theme_light() 

样本数据(.txt)

data_foo <- readr::read_csv("PID,Group,Session,Values
P1,F,1,14
P2,F,1,13
P3,F,1,16
P4,M,1,18
P5,F,1,20
P6,M,1,27
P7,M,1,19
P8,M,1,11
P9,F,1,28
P10,F,1,20
P11,F,1,24
P12,M,1,10
P1,F,2,26
P2,F,2,21
P3,F,2,19
P4,M,2,13
P5,F,2,26
P6,M,2,15
P7,M,2,23
P8,M,2,23
P9,F,2,30
P10,F,2,21
P11,F,2,11
P12,M,2,19")
ggplot2 plot bar-chart geom-bar
1个回答
1
投票

您遇到的麻烦是您想通过几组躲闪。您的geom_line不知道如何将Group变量除以session。这是解决此问题的两种方法,两者都需要更改x变量

1]按组创建“手动躲闪”,例如in this question,它也很有趣地回答了我的第一个问题。

2)使用interaction为每个Group分割会话。

我也改用了geom_point,因为geom_dot是直方图的一种特定类型。我通常建议使用箱形图对这样的值进行可视化,因为条形图更适合于诸如计数之类的特定度量。代码中的其他注释。

方法1:更改x变量并手动闪避

library(tidyverse)

data_foo <- data_foo %>% mutate(session = as.character(Session)) %>%
# this makes plotting easier
  mutate(dmeasure = ifelse(Group == "F", as.numeric(session) - .25, as.numeric(session) + .25 ))
# manual dodge

#Now the plot
ggplot(data_foo, aes(x = session, y = Values, fill = Group)) + 
  geom_bar(stat = "summary", fun.y = "mean", position = "dodge") + 
  geom_line(aes(x = dmeasure, group = PID)) +
  geom_point(aes(x = dmeasure, group = PID), shape = 21, color = 'black') 

“”

[方法2:在x变量中创建一个交互项

ggplot(data_foo, aes(x = interaction(Group,session), y = Values, fill = Group)) + 
  geom_bar(stat = "summary", fun.y = "mean", position = "dodge") +
  geom_line(aes(group = PID)) +
  geom_point(aes(group = PID), shape = 21, color = 'black') 

“”

reprex package(v0.3.0)在2020年1月15日创建

为了“以分组作为x变量按会话分组”:

ggplot(data_foo, aes(x = Group, y = Values, fill = interaction(Session,Group))) + 
  geom_bar(stat = "summary", fun.y = "mean", position = "dodge") + 
  geom_line(aes(x = dmeasure, group = PID)) +
  geom_point(aes(x = dmeasure, group = PID), shape = 21, color = 'black') 

这将为填充创建四个值,这可能不是您想要的。您可以手动定义相应的值以具有相同的值。但是,一切都会变得有些骇人听闻。

© www.soinside.com 2019 - 2024. All rights reserved.