R中的图形分类变量

Graph categorical variable in R

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")))

这是一个使用 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")