【问题标题】:Graph categorical variable in RR中的图形分类变量
【发布时间】:2018-04-30 10:33:59
【问题描述】:

Picture of how I want the graph to look

我有一个包含以下 3 个变量的数据集:

  1. 条件,分为 3 个级别:控制、眼睛、相机
  2. mean_destruction,连续,值范围在 0-10 之间,n=120
  3. mean_expectation,连续,范围在 0-10,n=120

例如:

df1 <- data.frame(Condition = c(rep('Control', 40), rep('Eyes', 40), rep('Camera', 40)),
                 mean_destruction = sample(0:10, 120, replace = T),
                 mean_expectation = sample(0:10, 120, replace = T)) 

我试图在 ggplot 2 中绘制此图,但失败了。这是我为重现下图所做的众多 ahem 努力之一:

ggplot(data=df1, aes(x= Condition, y=(mean.destruction), fill=(mean.expected)) +
    geom_bar(stat="identity", position=position_dodge(), colour="black")))

【问题讨论】:

  • 请注意上面的链接,上面是我真正想要实现的目标的图片 - 如果我们仍然手工完成所有事情,本可以在几个小时前完成!

标签: r ggplot2 categorical-data geom-bar


【解决方案1】:

这是一个使用 dplyr 和 tidyr 的答案。

我是这样解释你的数据的:

set.seed(2112)

df1 <- data.frame(Condition = c(rep('Control', 40), rep('Eyes', 40), rep('Camera', 40)),
                 mean_destruction = sample(0:10, 120, replace = T),
                 mean_expectation = sample(0:10, 120, replace = T)) 

您需要将数据转换为 long,以便为 destructionexpectation 获得不同的条形:

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

df1 <- df1 %>% 
      gather(mean_destruction, mean_expectation, key = mean_type, value = value) %>% 
      group_by(Condition, mean_type) %>% 
      summarize(mean = mean(value))

> df1
Source: local data frame [6 x 3]
Groups: Condition [?]

  Condition        mean_type  mean
     (fctr)            (chr) (dbl)
1    Camera mean_destruction  4.90
2    Camera mean_expectation  5.20
3   Control mean_destruction  4.85
4   Control mean_expectation  5.30
5      Eyes mean_destruction  4.40
6      Eyes mean_expectation  4.15

那么您的 ggplot2 调用只需要稍作调整:

ggplot(data=df1, aes(x = Condition, y = mean, fill = mean_type)) +
         geom_bar(stat="identity", position = 'dodge', colour="black")

【讨论】:

  • 这非常快 - 谢谢。 R 似乎无法找到“收集”功能,但我已经安装并调用了 dplyr。有什么想法吗? "function_list[[i]](value) 中的错误:找不到函数 "gather""
  • 知道了 - 这是一个“tidyr”功能。
  • 很抱歉,我认为上面的代码可能有错误 - 如果我运行它,数据会在以下情况下折叠为对 1 个变量的 1 次观察:group_by(Condition, mean_type) %>% summarise(mean = mean(value)) 如果我完全按照提供的方式运行上面的代码以尝试复制您所做的 BLT,并且如果我尝试将其调整到我的数据框,这都是正确的。
  • 对不起,我添加了库。我只是用干净的 R 会话运行它,它可以工作,所以可能是版本问题。我使用的是 R 版本 3.2.4、dplyr 0.4.3、ggplot2 2.1.0 和 tidyr 0.4.1。
  • 再次感谢您。现在工作正常。其他人注意:如果您同时运行 dplyr 和 plyr,它将不起作用。不知道为什么。感谢您的帮助,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
相关资源
最近更新 更多