0

I keep getting the following error and can't figure out what's going wrong. Please helps!

Error: Invalid input: date_trans works with objects of class Date only

My code is below.

#Problem 3b: Plot a line graph of the average monthly consumption in this population, with months on the x-axis running from January to December (1-12) and the consumption on the y axis.

rm(list=ls())
library(tidyverse)

# Read the discom_data.csv
discom_linegraph=read_csv("/Users/morgandenlow/Desktop/data_files/discom_data.csv")

#Aggregate consumption for each household annually for each year
electricity.utility.month = discom_linegraph %>% group_by(month) %>% summarise(monthly_consumption = mean(unitsconsumed,na.rm=TRUE))

electricity.utility.month$month = as.factor(electricity.utility.month$month)

data <- data.frame(electricity.utility.month$month)

#new date variable
electricity.utility.month$month <- as.Date(paste(electricity.utility.month$month, 1, sep="-"), format="%Y-%W-%w")


ggplot(data, aes(x = electricity.utility.month$month, y = electricity.utility.month$unitsconsumed)) 
+geom_line(color = "blue4") 
+ scale_x_date(date_breaks = "1 month", date_labels = "%b\n%Y") 
+scale_y_continuous(labels = NULL, limits = c(0, 100)) 
+labs(x = "Month", y = "Average consumption (kWh)",title = "Average consumption by month") 
+theme_bw() 
+theme(panel.grid.minor = element_blank(),panel.grid.major.x = element_blank(),plot.title = element_text(size = 14, face = "bold", hjust = 0.5))

Phil
  • 7,287
  • 3
  • 36
  • 66
Morgan
  • 1
  • 1
  • It looks like discom_linegraph doesn’t have 12 observations, but we can’t be sure because you haven’t shown us your data. It’s odd (and inconvenient!) to take your x variable from one data frame and your y variable from another. – Limey May 07 '21 at 22:27
  • Okay I've changed it so that y=electricity.utility.month$unitsconsumed and now i'm getting the Error: Invalid input: date_trans works with objects of class Date only – Morgan May 07 '21 at 22:33
  • It would be easier to help if you create a small reproducible example along with expected output. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah May 08 '21 at 05:59

1 Answers1

1

I don't have the data but you can try, don't convert month to factor.

electricity.utility.month$month = as.factor(electricity.utility.month$month)

skip this line.

Roach
  • 136
  • 5