【问题标题】:Error: Invalid input: date_trans works with objects of class Date only // Not sure how to fix错误:无效输入:date_trans 仅适用于 Date 类的对象 // 不确定如何修复
【发布时间】:2021-07-30 04:39:09
【问题描述】:

我不断收到以下错误,但不知道出了什么问题。请帮忙!

错误:输入无效:date_trans 仅适用于 Date 类的对象

我的代码如下。

#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))

【问题讨论】:

  • 看起来 discom_linegraph 没有 12 个观察值,但我们无法确定,因为您尚未向我们展示您的数据。从一个数据帧中获取 x 变量,从另一个数据框中获取 y 变量,这很奇怪(而且很不方便!)。
  • 好的,我已将其更改为 y=electricity.utility.month$unitsconsumed,现在我收到错误:输入无效:date_trans 仅适用于 Date 类的对象
  • 如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example

标签: r ggplot2 linegraph aesthetics


【解决方案1】:

我没有数据但是你可以试试,不要把month转换成factor

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

跳过这一行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多