2017-09-26 94 views
0

我想將一個黃土平滑擬合曲線添加到我在R的散點圖中。我似乎無法弄清楚我的代碼下面出現了什麼問題......僅供參考,變量povertybinge_all是數據幀correlational_data的列名。我已經加載了ggplot2包/庫。試圖將黃土平滑曲線添加到散點圖

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和類是因子。不知道這是否有所作爲。

更新,以顯示前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 
+2

'貧窮'和'binge_all'需要是'geom_smooth'的數字。如果您提供了所有您運行的相關代碼以及與您的代碼一起運行的數據樣本(例如,將您的問題粘貼到dput(correlational_data [1:10,])的輸出中, )'提供您的數據的前十行)。 – eipi10

+0

要檢查單個列的類:'class(correlational_data $ poverty)'。 'sapply(correlational_data,class)'將返回數據框中每一列的類。 – eipi10

+0

@ eipi10做了我發佈的更新幫助來回答你的問題? – PugFanatic

回答

0

的正如其他人在評論中指出,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 

enter image description here

請注意,如果你想你的因素列轉換爲數字,請轉換爲字符第一。下面是一個例子:

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

這將確保您轉換的實際數字,而不是因素的水平。

+0

一旦我將'貧窮'和'binge_all'改爲數字,我的代碼和一切工作都很棒!看起來好像全都跟這個班有關係。謝謝,非常有幫助! – PugFanatic