我每周都会从数据库中提取数据,并使用ggplot2绘制一些图表。 geom_smooth
这周不再出现。当我删除最后一条记录时,为什么?
样本数据
data <- structure(list(Status = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L), .Label = c("Cancelled",
"Closed", "In SAP", "Open"), class = "factor"), Year_Month = c("2017-06",
"2017-07", "2017-08", "2017-09", "2017-10", "2017-11", "2017-12",
"2018-01", "2018-02", "2018-03", "2018-04", "2018-05", "2018-06",
"2018-07", "2018-08", "2018-09", "2018-10", "2018-11", "2018-10",
"2018-11"), CNT = c(63L, 52L, 66L, 45L, 47L, 49L, 42L, 44L, 48L,
67L, 46L, 46L, 58L, 41L, 50L, 45L, 57L, 29L, 19L, 46L), per = c(67.74,
71.23, 70.97, 71.43, 78.33, 71.01, 63.64, 67.69, 53.93, 73.63,
60.53, 54.76, 81.69, 69.49, 63.29, 70.31, 69.51, 33.33, 23.17,
52.87), date = structure(c(17318, 17348, 17379, 17410, 17440,
17471, 17501, 17532, 17563, 17591, 17622, 17652, 17683, 17713,
17744, 17775, 17805, 17836, 17805, 17836), class = "Date")), .Names = c("Status",
"Year_Month", "CNT", "per", "date"), row.names = c(NA, -20L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), vars = "Year_Month", drop = TRUE, indices = list(
0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
14L, 15L, c(16L, 18L), c(17L, 19L)), group_sizes = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L), biggest_group_size = 2L, labels = structure(list(Year_Month = c("2017-06",
"2017-07", "2017-08", "2017-09", "2017-10", "2017-11", "2017-12",
"2018-01", "2018-02", "2018-03", "2018-04", "2018-05", "2018-06",
"2018-07", "2018-08", "2018-09", "2018-10", "2018-11")), row.names = c(NA,
-18L), class = "data.frame", vars = "Year_Month", drop = TRUE, .Names = "Year_Month"))
具有20条记录的图
ggplot(data,aes(x=date, y=per)) +
geom_point(aes(colour=Status),size=3) +
geom_smooth(method = 'loess',aes(group=data$Status, color=Status))
具有19条记录的图
data <- head(data,19)
答案 0 :(得分:3)
根据您要执行的操作/显示的内容,您可以:
1)通过在调用中指定geom_smooth
参数,仅将data
用于具有足够数据的组
ggplot(data,aes(x=date, y=per)) +
geom_point(aes(colour=Status),size=3) +
geom_smooth(data = data %>% filter(Status != "Open"), method = 'loess', aes(color = Status))
或
2)一起对所有数据使用geom_smooth
ggplot(data,aes(x=date, y=per)) +
geom_point(aes(colour=Status),size=3) +
geom_smooth(data = data, method = 'loess')
您看到的警告(根据@hrbrmstr的评论)来自loess
函数。我将检出?loess
。了解情节背后的内容总是有帮助的。
答案 1 :(得分:3)
作为一种一般的解决方案,可以做到:
library(ggplot2)
library(dplyr)
min_number <- 5 # set this to something reasonable of your choice
ggplot(data, aes(x = date, y = per, color = Status)) +
geom_point(size=3) +
geom_smooth(
data = . %>% group_by(Status) %>% filter(n() >= min_number),
method = 'loess'
)
仅对观察值至少min_number
的组绘制平滑。
答案 2 :(得分:1)
如注释中所述,geom_smooth
无法处理Open
状态组中的2个元素。有趣的是,可以使用1或3个元素。为了解决该问题,我决定从数据中排除Open
,并且它没有任何问题。
data2 <- data %>% dplyr::filter(Status!="Open")
ggplot(data,aes(x=date, y=per)) +
geom_point(aes(colour=Status),size=3) +
geom_smooth(data=data2,method = 'loess',aes(group=Status, color=Status))