为什么geom_smooth不会出现在分组的数据帧上?

问题描述 投票:0回答:1

我的数据框看起来像这样,在我看来,在各点之间划一条线应该毫无争议且容易,但没有出现。我收到一条新消息,说它正在使用公式y~x;当我以前使用这样的代码时没有出现。欢迎任何提示。使用ggplot2 3.3.1。

#My data
library(ggplot2)
dat<-structure(list(election = c("1965", "1968", "1972", "1974", "1979", 
"1980", "1984", "1988", "1993", "1997", "2000", "2004", "2006", 
"2008", "2011", "2015", "2019"), degree = c(1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), vote = c(3, 3, 3, 3, 3, 3, 
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), n = c(21L, 10L, 18L, 29L, 70L, 
55L, 73L, 70L, 43L, 95L, 63L, 70L, 105L, 122L, 246L, 239L, 225L
), pct = c(0.144827586206897, 0.072463768115942, 0.114649681528662, 
0.0900621118012422, 0.148619957537155, 0.155807365439093, 0.17016317016317, 
0.126811594202899, 0.0622286541244573, 0.116136919315403, 0.0813953488372093, 
0.159453302961276, 0.202702702702703, 0.148599269183922, 0.219642857142857, 
0.156005221932115, 0.130057803468208)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -17L), groups = structure(list(
    election = c("1965", "1968", "1972", "1974", "1979", "1980", 
    "1984", "1988", "1993", "1997", "2000", "2004", "2006", "2008", 
    "2011", "2015", "2019"), degree = c(1, 1, 1, 1, 1, 1, 1, 
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1), .rows = list(1L, 2L, 3L, 4L, 
        5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 
        17L)), row.names = c(NA, -17L), class = c("tbl_df", "tbl", 
"data.frame")))
# Do a check
head(dat)
#PLot Smooth does not show up
dat %>% 
  ggplot(., aes(x=election, y=pct))+geom_point()+geom_smooth()
r ggplot2 smoothing
1个回答
0
投票

问题是选举变量是一个字符。在将参数传递给ggplot之前将其转换为数字,或在aes中对其进行更改。

# Do a check
head(dat)
dat %>% 
    ggplot(.,aes(x=as.numeric(election), y=pct))+geom_point()+geom_smooth()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.