Reputation: 1148
I have a task and i need to plot graph using ggplot2. I have a vector of rating (Samsung S4 ratings from its users) I generate this data using this:
TestRate<- data.frame (rating=sample (x =1:5, size=100, replace=T ), month= sample(x=1:12,size=100,rep=T) )
And now I need to plot a graph, where on X axis will be dates (monthes in our example data) and 5 different lines grouped by 5 different ratings (1,2,3,4,5)
. Each line shows count of its ratings for corresponding month
How can I plot this in ggplot2?
Upvotes: 0
Views: 182
Reputation: 7654
If your data.table
is not set (so to speak), you can use dplyr
(and rename the legend while you are at it).
df <- TestRate %>% group_by(rating, month) %>% summarise(count = n())
ggplot(df, aes(x=month, y=count, color=as.factor(rating))) + geom_line() + labs(color = "Rating")
Upvotes: 0
Reputation: 31161
You need first to count the number of elements per couple of (rating, month):
library(data.table)
setDT(TestRate)[,count:=.N,by=list(month, rating)]
And then you can plot the result:
ggplot(TestRate, aes(month, count, color=as.factor(rating))) + geom_line()
Upvotes: 3