【问题标题】:ggplot matrix with x,y and color=category using loopsggplot 矩阵与 x,y 和 color=category 使用循环
【发布时间】:2019-11-12 20:22:39
【问题描述】:

我正在尝试运行一个简单的绘图列表来评估我在 R 中的分配的正确线性回归模型。基本上在 11 列中,第 1 列是 y,不同的列 x = 3:11 是 theta或 y 所依赖的变量。第 2 列的分类值基本上是 1-9(9 个类别)。

我正在尝试创建图形矩阵。我可以一张一张地做图表,这应该适用于分配,但我试图使用单个循环来完成它。代码如下:

第 1 列是 y,因变量和第 3-11 列是变量。如果我根据第 2 列省略着色,我可以用一个基图来完成它。如果我尝试上面的代码,我不会得到任何情节

par(mfrow(3,3))
for(i in 3:11){
  ggplot(hd,aes(x=hd[1,],y=hd[,i],color=hd[,2]))+
  geom_point()
}

编辑: 这是一个可重现的数据

library(dplyr)
library(ggplot2)
hd=data(economics)

par(mfrow(2,2))
    for(i in 3:6){
      ggplot(hd,aes(x=hd[3,],y=hd[,i])+
      geom_point()
    }

这没有颜色分类,但如果我可以让它工作,我可以添加 color= 列参数

【问题讨论】:

标签: r ggplot2


【解决方案1】:

如果我了解您的需求,那么以下内容应该可以工作。首先,制作一些与您描述的大致相似的可重现数据:

library(magrittr)
library(tidyverse)
data <- tibble(y = rnorm(10), 
               category = factor(sample(1:9, 10, replace = TRUE))) %>% 
  inset(paste0("x", 1:11), value = rnorm(110)) %>%
  pivot_longer(-c(y, category), names_to = "x_name", values_to = "x")

数据如下:

# A tibble: 6 x 4
      y category x_name      x
  <dbl> <fct>    <chr>   <dbl>
1  1.84 6        x1      1.06 
2  1.84 6        x2      0.744
3  1.84 6        x3     -1.19 
4  1.84 6        x4      1.88 
5  1.84 6        x5      2.16 
6  1.84 6        x6     -1.58

然后您可以在此处使用facet_wrap 创建一个网格,其中每个x_name 都有一个面板。我已经添加了geom_smooth 以进行良好的衡量:

ggplot(data, aes(x = x, y = y)) +
  geom_point(aes(colour = category)) +
  facet_wrap(~x_name) +
  geom_smooth(method = "lm")

【讨论】:

    【解决方案2】:

    我也鼓励你提供一个可重现的例子。

    ggplot 使用 facetting 的概念,而不是“par(mfrow)”。看看这里:ggplot facetting

    library(tidyr)
    library(dplyr)
    library(ggplot2)
    
    # assuming the names of your dataframe hd are like this:
    names(hd) = c('y', 'cat', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9')
    
    # then, the following code could solve your problem:
    hd %>% 
      pivot_longer(x1:x9, names_to=var_x, values_to=val_x) %>% 
      ggplot(hd, aes(x=y, y=val_x, colour=cat)) +
      geom_point() +
      facet_wrap(~var_x, ncol=3)
    

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 2020-02-13
      • 1970-01-01
      相关资源
      最近更新 更多