【发布时间】:2018-11-27 18:45:36
【问题描述】:
我遇到了 geom_smooth() 在我的 ggplot 上不起作用的问题。根据以前的帖子,我发现因为我的日期变量是字符向量,所以 geom_smooth() 不起作用。我正在尝试将我的日期从类字符转换为类日期,但使用 as.Date 会导致我的日期变量的类“未知”。
这是我尝试修复我的类类型的代码:
allmovies <- allmovies %>%
clean_names() %>%
select(movie, total_box_office, theatrical_release_release_date,
running_time, mpaa, metacritic, sentiment) %>%
mutate(theatrical_release_release_date =
as.character(theatrical_release_release_date)) %>%
mutate(theatrical_release_release_date = as.Date(theatrical_release_release_date, format = "%Y-%m-%d"))
这是我尝试使用 geom_smooth() 进行绘图的代码,以防有人可以帮助我在这里找到错误。
ggplotly(tooltip = c("text"),
ggplot(data = allmovies, aes(x = theatrical_release_release_date,
y = total_box_office, color = mpaa, text = movie)) +
geom_point() +
geom_smooth(method=lm) +
scale_y_continuous(labels = comma) +
labs(color = "MPAA Rating") +
ylab("Total Box Office Revenue") +
xlab("Theatrical Release Date") +
ggtitle("Total Box Office Revenue Over Time",
subtitle = "While revenue generally improved over time, a further analysis shows PG rated movies generated much more revenue over time while PG-13 and R-rated revenue correlations do not appear to be significant.")) %>%
layout(title = "Total Box Office Revenue Over Time",
font = font)
最后,这是我的日期列数据示例:
dput(head(allmovies$theatrical_release_release_date))
c("2013-08-23", "2013-03-22", "2012-09-14", "2012-03-16", "2012-02-17",
"2011-10-14")
这里是整个数据的一个小样本:
structure(list(movie = c("The Frozen Ground", "The Croods", "Stolen", "Seeking Justice", "Ghost Rider: Spirit of Vengeance", "Trespass" ), total_box_office = c(5617460, 573068425, 17967746, 411746, 149217355, 786532), theatrical_release_release_date = structure(c(15940, 15786, 15597, 15415, 15387, 15261), class = "Date"), running_time = c(105, 98, 96, 104, 95, 90), mpaa = c("R", "PG", "R", "R", "PG-13", "R"), metacritic = c(37, 55, 43, 38, 34, 37), sentiment = c(NA, 0.1363636, NA, NA, NA, NA)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
【问题讨论】:
-
嗨克莱尔。提供一些有关您正在使用的 R 版本、您已加载的任何包和操作系统的信息可能会有所帮助。
-
请提供您的数据样本,因为问题可能是由于您的日期列的某些特征造成的。
-
我们确实没有足够的信息来提供帮助。您共享的日期的小示例转换为日期对我来说很好,具有适当的类。情节未按预期运行可能还有很多其他原因,但如果没有可以运行的完整工作示例来展示您所看到的整个行为,我们就无法真正进行调查。
-
我认为可能是
text = movie导致ggplot尝试为每部电影拟合模型。尝试删除它。 -
您可能只希望
geom_point层中的文本美观。当您将它们放在顶部的ggplot()调用中时,每个后续层都会继承所有这些美学映射。而且你不希望他们都在geom_smooth()。
标签: r ggplot2 dplyr tidyverse as.date