0

Using an example dataframe:

 df <- structure(list(value = c(10L, 8L, 6L, 4L, 2L, 9L, 7L, 5L, 3L, 
    1L, 1L, 1L, 2L, 3L, 4L, 3L, 3L, 4L, 5L, 2L, 2L, 4L, 6L, 4L, 7L, 
    3L, 5L, 4L, 6L, 3L), length = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 
    4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 
    5L, 1L, 2L, 3L, 4L, 5L), wave = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 
    3L, 3L, 3L, 3L, 3L, 3L, 3L)), .Names = c("value", "length", "wave"
    ), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
    -30L), spec = structure(list(cols = structure(list(value = structure(list(), class = c("collector_integer", 
    "collector")), length = structure(list(), class = c("collector_integer", 
    "collector")), wave = structure(list(), class = c("collector_integer", 
    "collector"))), .Names = c("value", "length", "wave")), default = structure(list(), class = c("collector_guess", 
    "collector"))), .Names = c("cols", "default"), class = "col_spec"))

I wish to plot the average 'value' (line graph) by 'length' for each group (wave).

Is this possible direct from ggplot? (or do I need to do the preliminary analysis first).

I would have otherwise used:

ggplot(df, aes(x=length, y=value, color=wave)) + geom_point(shape=1)

1 Answer 1

1

We can use stat_summary for this task

library(ggplot2)
ggplot(df, aes(x = length, y = value, col = as.factor(wave))) + 
  stat_summary(geom = "line", fun.y = mean)

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Markus. A few observations when I run my full data. Firstly - my length runs from 1-10. But when I look at the graph it goes 1, 10, 2, 3, 4... is it possible to specify how the numbers run? Secondly the graph doesn't form and I get geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic? What should I do?
Is your length column a factor by any chance? For the error: try group = factor(wave) inside ggplot(). Above, I used col instead. If still not working, edit your question and use dput() to share your data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.