2017-07-04 74 views
0
df1 <- data.frame(a=c(1,4,7), 
       b=c(3, 5, 6), 
       c=c(1, 1, 4), 
       d=c(2 ,6 ,3)) 
df2<-data.frame(id=c("a","f","f","b","b","c","c","c","d","d"), 
      var=c(12,20,15,18,10,30,5,8,5,5)) 

mediorder <- with(df2, reorder(id, -var, median)) 
boxplot(var~mediorder, data = df2) 

fc = levels(as.factor(mediorder)) 
ndf1= df1[,intersect(fc, colnames(df1))] 

ln<-lm(#confused here 

boxplot(ndf1) 
abline(ln) 

我有上面的盒子圖(ndf1),x軸根據另一個數據框架,我想添加一個趨勢線。如何在訂購x軸時將趨勢線添加到計數(y軸)和ID(x軸)的盒圖中

我很困惑,因爲它沒有x和y變量來引用,只是有計數的列。此外,排序造成我的問題。

編輯以澄清... 我建立在這裏的問題是:How to match an ordered list (e.g., levels(as.factor(x))) to another dataframe in which only some columns match?

所有我想要做的就是適應趨勢線ndf1

+0

你的問題是非常混亂。你應該澄清它。例如,因子「a」只有一個值(12),所以「d」。 –

+0

作爲唯一的例子它並不重要。 – joey5

+0

嗯,我認爲這不是正確的例子,因爲你正在製作一個帶有一個值的boxplot。 –

回答

0

這樣的事情應該做的。使用ggplot2相當簡單。但是,您的數據/問題有點令人困惑,例如有些因素(a,d)只有一個數據點。這是你想要的嗎?

df2$id <- factor(df2$id , levels = levels(mediorder)) 
library(ggplot2) 
ggplot(data = df2, aes(x = id, y = var)) + geom_boxplot() + 
    geom_smooth(method = "lm", aes(group = 1), se = F) 

enter image description here

+0

趨勢線應該適合nfd1 – joey5

+0

@ joey5,你是說你的迴歸線應該來自一個不同的數據框,其中包含了你在箱形圖數據中有什麼不同的因素?什麼是grp? –

+0

對不起。 grp僅僅是我用來匹配我的數據的示例代碼。 – joey5