如何根据数据框的多列中的特征创建散点图?

时间:2017-10-05 15:16:42

标签: r plot

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种单独的颜色,每种颜色具有不同的趋势线。

如何做到这一点?

我希望这是可以重复和清晰的。我只发了几次,所以我还是习惯了这种格式。

谢谢!

2 个答案:

答案 0 :(得分: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是点类型(实心点)。

答案 1 :(得分: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