首页 文章

ggplot2中连续变量的方面[重复]

提问于
浏览
9

可能重复:ggplot - 按功能输出的facet

ggplot2facets 选项很适合按因子显示多个图,但我在学习有效地将连续变量转换为其中的因子时遇到了麻烦 . 使用以下数据:

DF <- data.frame(WindDir=sample(0:180, 20, replace=T), 
                 WindSpeed=sample(1:40, 20, replace=T), 
                 Force=sample(1:40, 20, replace=T))
qplot(WindSpeed, Force, data=DF, facets=~cut(WindDir, seq(0,180,30)))

我收到错误: At least one layer must contain all variables used for facetting

我想通过离散的30度间隔检查关系 Force~WindSpeed ,但似乎 facet 要求将因子附加到正在使用的数据框上(显然我可以做 DF$DiscreteWindDir <- cut(...) ,但这似乎是不必要的) . 有没有办法在将连续变量转换为因子时使用 facets

1 回答

  • 6

    举例说明如何使用 transform 进行内联转换:

    qplot(WindSpeed, Force,
          data = transform(DF,
                           fct = cut(WindDir, seq(0,180,3))),
          facets=~fct)
    

    你没有使用faceting变量"pollute" data ,但是它位于ggplot的数据框中(而不是facet规范中的列的函数) .

    这在扩展语法中也同样有效:

    ggplot(transform(DF,
                     fct = cut(WindDir, seq(0,180,3))),
           aes(WindSpeed, Force)) +
      geom_point() +
      facet_wrap(~fct)
    

相关问题