bvowe
bvowe

Reputation: 3384

GGPlot With Specifications

data=data.frame("grade"=c(1, 2, 3, 1, 2, 3),
                "class"=c('a', 'a', 'a', 'b', 'b', 'b'),
                "size"=c(1, 1, 2, 2, 2, 1),
                "var"=c('q33', 'q35', 'q39', 'q33', 'q35', 'q39'),
                "score"=c(5, 8, 7, 3, 7, 5))

My data have many group variables. First I want to just plot 'score' by 'grade' with a line

library(reshape2, ggplot2)
ggplot(data, aes(x = grade, y = score)) + geom_line()

It gives a funny graph because I have 'grade' repeated for different classes and sizes. If I take a subset of my data then the graph looks ok.

ggplot(subset(data, size == 1), aes(x = grade, y = score)) + geom_line()

So I wonder how can I plot my data 'score' by 'grade' for ALL combinations without the graph somehow combining all values?

Upvotes: 0

Views: 79

Answers (2)

You could use facet_wrap(~class+size) this will give one plot per combination.

Upvotes: 1

Ben
Ben

Reputation: 30474

Here is one approach. You can plot score vs. grade, and use stat_summary to add a line going through mean at each grade, and a ribbon that contains the 95% confidence interval. Is this what you had in mind?

library(ggplot2)

ggplot(data = data, mapping = aes(x = grade, y = score)) +
  stat_summary(geom = "line", fun = mean, linetype = "dashed") +
  stat_summary(geom = "ribbon", fun.data= mean_cl_normal, fun.args = list(conf.int=0.95), alpha=.1) +
  scale_x_continuous(breaks = data$grade)

Plot

plot with mean and 95% CI

Alternatively, you can plot points for mean values at each grade and standard error bars.

library(tidyverse)

data %>%
  group_by(grade) %>%
  summarise(mean_score = mean(score),
            SD = sd(score),
            n = n(),
            SE = SD/sqrt(n)) %>%
  ggplot(mapping = aes(x = grade, y = mean_score)) +
  geom_point() +
  geom_line() +
  geom_errorbar(aes(ymin = mean_score - SE, ymax = mean_score + SE), width = .1) +
  scale_x_continuous(breaks = data$grade)

Plot

plot with mean points and standard errors

Upvotes: 1

Related Questions