2017-10-05 44 views
0
age <- rnorm(100, 0:100) 
freq <- rnorm(100, 0:1) 
char1<-stringi::stri_rand_strings(100, length = 1, pattern = "[abc]") 
char2<-stringi::stri_rand_strings(100, length = 1, pattern = "[def]") 
char3<-stringi::stri_rand_strings(100, length = 1, pattern = "[def]") 
char3<-stringi::stri_rand_strings(100, length = 1, pattern = "[ghi]") 
dftest <- data.frame(age, freq, char1, char2, char3) 
dflist <- list(dftest, dftest, dftest, dftest, dftest) 

這將創建一個示例數據框架,演示我遇到的問題。如何根據數據框的多列中的特徵創建散點圖?

我想爲列表中的每個數據框創建年齡與頻率的散點圖,但是我想根據列「char#」中的值爲點創建不同的顏色。我還需要一個單獨的趨勢線來表示這些獨立特徵中的每一個的值。

我也希望能夠根據不同char列的不同特徵的組合來做到這一點。其中一個例子是每種組合的3 * 3 = 9種顏色,每種顏色都有不同的趨勢線。

這將如何完成?

我希望這是足夠重複和清晰的。我只發佈了幾次,所以我仍然習慣了這種格式。

謝謝!

+0

在您所提供的數據,數據幀的都是相同的,所以即使你彩色他們不同的列表,你只會看到一組點。假設你有真實的數據看起來不同於這個,你首先需要爲每個數據框添加一個id列,然後將它們全部「綁定」在一起,然後將顏色映射到id。對於您提供的示例,您的ID將爲1-5 – Mako212

+0

查看ggplot2。聽起來最適合這個問題。嘗試使用方面。 – Jimbou

回答

0

首先讓我們來創建一個數據幀,讓我們展現出點用不同的顏色:

df2 <- data.frame(age=rnorm(200,0:100), 
    freq=rnorm(200,0:1),id=rep(1:2,each=100)) 

然後我們就可以plot像這樣:

plot(dflist2$age,dflist2$freq, col=dflist2$id, pch=16) 

我們設置col(顏色)等到id(這將代表每個數據幀)。 pch是點類型(實心圓點)。

0

您可以嘗試使用dplyr進行數據準備,並使用ggplot進行繪圖。所有功能都通過tidyverse包裝:

library(tidyverse) 
# age vs freq plus trendline for char1 
as.tbl(dftest) %>% 
    ggplot(aes(age, freq, color=char1)) + 
    geom_point() + 
    geom_smooth(method = "lm") 

enter image description here

# age vs freq plus trendline for combinations of char columns 
as.tbl(dftest) %>% 
    unite(combi, char1, char2, char3, sep="-") %>% 
    ggplot(aes(age, freq, color=combi)) + 
    geom_point() + 
    geom_smooth(method = "lm") 
# no plot as too many combinations make the plot to busy 
dflist %>% 
    bind_rows(.id = "df_source") %>% 
    ggplot(aes(age, freq, color=char1)) + 
    geom_point() + 
    geom_smooth(method = "lm", se=FALSE) + 
    facet_wrap(~df_source) 

enter image description here

+0

對不起,我可能應該在問題中提到過這個問題,但是可以在圖上顯示每個線性模型的Spearman相關p值和rho值嗎? – user8384020

+0

是的,這是可能的。看看'ggpubr'或'ggsignify'包。請注意,「lm」是一種參數化方法。 – Jimbou

相關問題