Reputation: 379
I am working on creating one plot with multiple non-discreet count variables. I have three separate count variables that are plotted by month. I have a solution but I feel that its probably not the most parsimonious and limited.
df_test <- structure(list(total = c(323L, 263L, 171L,
12L, 6L, 59L, 253L, 187L, 161L, 160L, 136L, 185L, 6L), month_name = structure(c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, NA), .Label = c("Jan",
"Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
"Nov", "Dec"), class = "factor"), neg = c(268L,
231L, 146L, 10L, 6L, 55L, 237L, 177L, 140L, 131L, 107L, 155L,
3L), pos = c(55, 32, 25, 2, 0, 4, 16, 10, 21,
29, 29, 30, 1)), row.names = c(NA, -13L), class = c("tbl_df",
"tbl", "data.frame"))
ggplot() +
geom_line(data = na.omit(df_test), aes(x=month_name, y=total), colour = "blue", group=1) +
geom_line(data = na.omit(df_test), aes(x=month_name, y=neg), colour = "black", group=1) +
geom_line(data = na.omit(df_test), aes(x=month_name, y=pos), colour = "red", group=1) +
xlab("Month") +
ylab("Count")
So this is what I want but I figure since the data are all in the same data frame there is probably a more parsimonious way where I can then edit a legend and also add points.
Thanks!
Upvotes: 0
Views: 533
Reputation: 907
try this, this should let you edit legend names etc:
df_test2<-pivot_longer(df_test, cols = c("neg", "pos", "total")) %>%
ungroup()
df_test2 %>%
ggplot(.) + geom_point(aes(x=month_name, y = value, color = name)) +
geom_line(aes(x=as.numeric(month_name), y = value, color = name)) +theme_classic()
Upvotes: 1
Reputation: 2584
Just reshape your data:
m <- reshape2::melt(df_test,id.vars="month_name")
ggplot(na.omit(m),aes(x=month_name,y=value,group=variable,col=variable)) +
geom_line()
From here you can customize the plot as you want
Upvotes: 3