在ggplot2

时间:2018-02-06 22:25:06

标签: r plot ggplot2 grouping

我正在尝试制作一个在y轴上具有ID的平均值(+/- SD)(Explorations =每行总计数)的图,然后按{{{}}进行分组在x轴上1}}和pp

也就是说,我想生成一些看起来像这样的东西(手绘和组成图形): enter image description here

以下是数据框的结构(可用here)。

type

我想使用pp crossingtype km type ID 0 Complete 80.0 DCC 10 1 Complete 80.0 DCC 4 0 Exploration 80.0 DCC 49 1 Exploration 80.0 DCC 4 0 Complete 144.0 DWC 235 1 Complete 144.0 DWC 22 0 Exploration 144.0 DWC 238 1 Exploration 144.0 DWC 18 1 Exploration 84.0 PC 40 0 Complete 107.0 PC 43 1 Complete 107.0 PC 22 0 Exploration 107.0 PC 389 并尝试过此代码:

ggplot2

但它给了我这个数字(这不是我想要做的)。 enter image description here

如何使用ggplot(expMean, aes(x=as.factor(pp), y=crossingtype, color=factor(type),group=factor(type))) + geom_point(shape=16,cex=3) + geom_smooth(method=lm) + facet_grid(.~type) 制作第一张图?

3 个答案:

答案 0 :(得分:1)

这是你想要的吗?这会将数据过滤为仅包含Exploration,使用ID作为y变量,pp分组和type上的分面

tbl <- read_table2(
  "pp crossingtype  km  type ID
  0     Complete  80.0  DCC  10
  1     Complete  80.0  DCC   4
  0  Exploration  80.0  DCC  49
  1  Exploration  80.0  DCC   4
  0     Complete 144.0  DWC 235
  1     Complete 144.0  DWC  22
  0  Exploration 144.0  DWC 238
  1  Exploration 144.0  DWC  18
  1  Exploration  84.0   PC  40
  0     Complete 107.0   PC  43
  1     Complete 107.0   PC  22
  0  Exploration 107.0   PC 389"
) %>%
  mutate(pp = factor(pp))

ggplot(data = tbl %>% filter(crossingtype == "Exploration")) +
  geom_boxplot(aes(x = pp, y = ID)) + 
  facet_wrap(~type)

我在链接数据集上运行此代码以生成此代码:

Boxplot for entire linked dataset

答案 1 :(得分:1)

你可以在ggplot()内进行统计变换,但我首先要处理数据,然后绘制结果。

library(tidyverse)
expMean %>% 
  filter(crossingtype == "Exploration") %>% 
  group_by(type, pp) %>% 
  summarise(Mean = mean(ID), SD = sd(ID)) %>% 
  ggplot(aes(factor(pp), Mean)) + 
    geom_pointrange(aes(ymax = Mean + SD, 
                        ymin = Mean - SD)) + 
    facet_wrap(~type) +
    theme_bw()

enter image description here

答案 2 :(得分:1)

这是我使用的方法。使用颜色而不是双值x轴。

请注意,我已将数据下载到我的工作目录,因此可能需要修改read.table命令

library(dplyr)
library(ggplot2)
dat <- read.table("figshare.txt")

dat <- droplevels(filter(dat, crossingtype == "Exploration"))
dat <- dat %>%
  group_by(pp, type) %>% 
  summarise(val = mean(ID),
        SD = sd(ID))

ggplot(dat, aes(x = type, y = val, colour = as.factor(pp), group = 
     as.factor(pp))) +
  geom_point(size = 3, position = position_dodge(width = 0.2)) +
  geom_errorbar(aes(ymax = val + SD, ymin = val - SD), position = 
     position_dodge(width = 0.2), width = 0.2) +
  labs(y = "Mean # of explorations (+/- SD", colour = "pp")

enter image description here