1

I am working with the ggplot library in R. Is it possible to plot irregular sized objects on the same graph?

Suppose I data like this:

library(dplyr)
library(ggplot2)

date= seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")

var <- rnorm(731,10,10)


group <- sample( LETTERS[1:4], 731, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )

data = data.frame(date, var, group)

data$year = as.numeric(format(data$date,'%Y'))
data$year = as.factor(data$year)

If I aggregate the data by group:

data %>%
    mutate(date = as.Date(date)) %>%
    group_by(group, month = format(date, "%Y-%m")) %>%
    summarise( mean = mean(var, na.rm = TRUE), Count = n())

It then seems there is no straightforward way to plot all the data at once:

ggplot(data) +
    geom_line(aes(x=date, y=mean, colour=group, group=1))+
    scale_x_date(date_breaks = "months" ,breaks = '12 months', date_labels = "%b %d %a")+
    scale_colour_manual(values=c("red","green","blue", "purple"))+
    theme(axis.text.x = element_text(angle=90))

Error: Aesthetics must be either length 1 or the same as the data (263): x

Can this data be plotted all together? Or does it have to be plotted seperately?

stats_noob
  • 5,401
  • 4
  • 27
  • 83

1 Answers1

1

Try with this:

library(ggplot2)
#Code
New <- data %>%
  mutate(date = as.Date(date)) %>%
  group_by(group, month = format(date, "%Y-%m")) %>%
  summarise( Mean = mean(var, na.rm = TRUE), Count = n())
#Format
New <- as.data.frame(New)
#Plot
ggplot(New) +
  geom_line(aes(x=month, y=Mean, colour=group,group=1))+
  scale_colour_manual(values=c("red","green","blue", "purple"))+
  theme(axis.text.x = element_text(angle=90))

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
  • thank you for your reply! your reply helped me post my next question! https://stackoverflow.com/questions/65676788/combining-different-types-of-graphs-together-r :) i am slowly learning! – stats_noob Jan 12 '21 at 01:23