尝试将黄土平滑曲线添加到散点图

Trying to Add Loess Smoothing Curve to Scatterplot

我正在尝试向 R 中的散点图添加黄土平滑拟合曲线。我似乎无法弄清楚下面的代码有什么问题...供参考,变量 povertybinge_all 是数据框 correlational_data 的列名。我已经加载了 ggplot2 package/library。

library(ggplot2)    

p <- ggplot(correlational_data, aes(poverty, binge_all))
p <- p + geom_point(color = "blue")
p <- p + geom_smooth(method = "loess")
p

我用sapply(correlational_data$poverty, class)sapply(correlational_data$binge_all, class)确定povertybinge_all是class因子。不确定这是否有所作为。

更新以显示前 10 行数据

head(correlational_data, 10)
   year                state binge_all poverty
1  2012              Alabama      12.3      19
2  2012               Alaska      16.8    10.1
3  2012              Arizona      15.3    18.7
4  2012             Arkansas      11.8    19.8
5  2012           California      16.9      17
6  2012             Colorado      19.2    13.7
7  2012          Connecticut      17.5    10.7
8  2012             Delaware      18.6      12
9  2012 District of Columbia      23.1    18.2
10 2012              Florida      16.5    17.1

正如其他人在评论中指出的那样,binge_allpoverty 需要是数字,而不是因子。在这里,我使用您提供的代码和示例数据绘制数据。

# Create example data frame
correlational_data <- read.table(text = "   year                state binge_all poverty
1  2012              Alabama      12.3      19
                                 2  2012               Alaska      16.8    10.1
                                 3  2012              Arizona      15.3    18.7
                                 4  2012             Arkansas      11.8    19.8
                                 5  2012           California      16.9      17
                                 6  2012             Colorado      19.2    13.7
                                 7  2012          Connecticut      17.5    10.7
                                 8  2012             Delaware      18.6      12
                                 9  2012 'District of Columbia'      23.1    18.2
                                 10 2012              Florida      16.5    17.1",
                                 header = TRUE, stringsAsFactors = FALSE)

# Check the class
class(correlational_data$binge_all)
[1] "numeric"
class(correlational_data$poverty)
[1] "numeric"

# Plot the data   
library(ggplot2)

p <- ggplot(correlational_data, aes(poverty, binge_all))
p <- p + geom_point(color = "blue")
p <- p + geom_smooth(method = "loess")
p

请注意,如果您想将因子列转换为数值,请先转换为字符。下面是一个例子:

correlational_data$binge_all <- as.numeric(as.character(correlational_data$binge_all))
correlational_data$poverty <- as.numeric(as.character(correlational_data$poverty))

这将确保您转换的是实际数字,而不是因子的水平。