R ggplot多个系列曲线

时间:2015-10-22 20:35:46

标签: r ggplot2

我正在一个地块上绘制多个系列的数据。

我的数据如下:

count_id    AMV Hour    duration_in_traffic AMV_norm
1   16012E  4004    14  99  0
2   16012E  4026    12  94  22
3   16012E  4099    15  93  95
4   16012E  4167    11  100 163
5   16012E  4239    10  97  235

我正在用R绘图:

ggplot(td_results, aes(AMV,duration_in_traffic)) + geom_line(aes(colour=count_id))

这给了我:

AMV versus Duration_in_traffic

然而,我想弯曲而不是直线连接点。

我发现了以下问题但得到了意想不到的输出。 Equivalent of curve() for ggplot

我用过:ggplot(td_results, aes(AMV,duration_in_traffic)) + geom_line(aes(colour=count_id)) + stat_function(fun=sin)

这样给予:

Plot using stat_function(fun=sin)

如何获得具有某种形式的高阶多项式的曲线?

1 个答案:

答案 0 :(得分:1)

正如@MrFlick在评论中提到的那样,有一些严肃的统计方法可以获得曲线,这可能与此不同。

如果您只是希望图表看起来更漂亮,可以尝试使用spline插入数据,然后将其添加为另一个图层。

首先,我们使用您拥有的数据点数的10倍来制作一些样条数据(您可以根据需要增加或减少数据点):

library(dplyr)
dat2 <- td_results %>% select(count_id, AMV, duration_in_traffic) %>%
                group_by(count_id) %>%
                do(as.data.frame(spline(x= .[["AMV"]], y= .[["duration_in_traffic"]], n = nrow(.)*10)))

然后我们使用原始数据绘制点,然后使用样条数据中的线(dat2):

library(ggplot2)
ggplot(td_results, aes(AMV, duration_in_traffic)) +
   geom_point(aes(colour = factor(count_id))) +
   geom_line(data = dat2, aes(x = x, y = y, colour = factor(count_id)))

这为我提供了测试数据中的以下图表: enter image description here