【问题标题】:How to plot using multiple criteria in R?如何在 R 中使用多个标准进行绘图?
【发布时间】:2014-01-28 07:40:57
【问题描述】:

以下是我的数据的前 15 行:

> head(df,15)
   frame.group class lane veh.count mean.speed
1     [22,319]     2    5         9   23.40345
2     [22,319]     2    4         9   24.10870
3     [22,319]     2    1        11   14.70857
4     [22,319]     2    3         8   20.88783
5     [22,319]     2    2         6   16.75327
6    (319,616]     2    5        15   22.21671
7    (319,616]     2    2        16   23.55468
8    (319,616]     2    3        12   22.84703
9    (319,616]     2    4        14   17.55428
10   (319,616]     2    1        13   16.45327
11   (319,616]     1    1         1   42.80160
12   (319,616]     1    2         1   42.34750
13   (616,913]     2    5        18   30.86468
14   (319,616]     3    3         2   26.78177
15   (616,913]     2    4        14   32.34548

“frame.group”包含时间间隔,“class”是车辆类别,即 1=摩托车、2=汽车、3=卡车,“lane”包含车道编号。我想创建 3 个散点图,frame.group 作为 x 轴,mean.speed 作为 y 轴,每个类 1 个。在一个车辆类别的散点图中,例如汽车,我想要 5 个地块,即每条车道一个。我尝试了以下操作:

cars <- subset(df, class==2)
by(cars, lane, FUN = plot(frame.group, mean.speed))

有两个问题:

1) R 没有按预期绘制,即 5 个不同车道的 5 个图。 2) 只绘制了一个,这也是箱线图,可能是因为我使用区间而不是数字作为 x 轴。

如何解决上述问题?请帮忙。

【问题讨论】:

    标签: r plot


    【解决方案1】:

    每次发出新的绘图命令时,R 都会用新绘图替换现有绘图。您可以通过par(mfrow=c(1,5)) 创建一个绘图网格,这将是 1 行和 5 个绘图(其他数字将具有其他数量的行和列)。如果你想要一个散点图而不是箱线图,你可以使用plot.default

    使用 ggplot2 库而不是基础图形更容易完成所有这些操作,并且生成的绘图看起来会更好:

    library(ggplot2)
    ggplot(cars,aes(x=frame.group,y=mean.speed))+geom_point()+facet_wrap(~lane)
    

    查看 ggplot2 文档了解更多详情:http://docs.ggplot2.org/current/

    【讨论】:

    • 谢谢。到目前为止,我一直在避免使用 ggplot2。但现在是学习它的时候了。你给了我动力,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多