Reputation: 959
I am new to R/ggplot2 and am trying to create a line graph of counts (or percentages, it doesn't matter) for responses to 6 stimuli in ggplot in R. The stimuli should go across the x-axis, and the count on the y-axis. One line will represent the number of participants who responded with a preposition, and the other line will represent the number of participants who responded with a number.
I believe that ggplot with geom_line() requires an x and y (where y is the count or percentage).
Should I create a new data frame with count so that I can use ggplot? And then, a subquestion would be how do I count responses based on the stimulus data (so, how do I count response based on another column in the data frame, or how many preposition responses for stimulus 1, how many number responses for stimulus 1, how many preposition responses for stimulus 2, etc. Maybe with some kind of if statement?)?
or
Is there a way to automatically produce these counts in ggplot?
Of course, it's entirely possible that I'm going about this the wrong way entirely.
I've tried to search this, but cannot find anything. Thank you so much.
Upvotes: 4
Views: 4787
Reputation: 959
As I said in my comment, I ended up creating a frequency table and using ggplot to plot the resulting data frame. Here's the code below!
# creates data frame
resp <- c("number", "number", "preposition", "number")
sound <- c(1, 1, 2, 2)
df <- data.frame(resp, sound)
# creates frequency table
freq.table <- prop.table((xtabs(~resp+sound, data=df)), 2)
freq.table.df <- as.data.frame(freq.table)
# plots lines based on frequency
ggplot(freq.table.df, aes(sound, Freq, group=resp, color=resp)) +
geom_line()
Upvotes: 1