如何制作运动物体的速度曲线?

时间:2018-12-02 22:28:44

标签: r performance plot profile

我是R初学者用户,因此遇到以下问题。我有以下数据框:

       distance speed
1      61.0  36.4
2      51.4  35.3
3      42.2  34.2
4      33.4  32.8
5      24.9  31.3
6      17.5  28.4
7      11.5  24.1
8       7.1  19.4
9       3.3  16.9
10      0.5  15.5
11      4.4  15.1
12      8.5  15.5
13     13.1  17.3
14     18.8  20.5
15     25.7  24.1
16     33.3  26.3
17     41.0  27.0
18     48.7  27.7
19     56.6  28.4
20     64.8  29.2
21     73.6  31.7
22     83.3  34.2
23     93.4  35.3

列距离表示跟随的对象在特定点上的距离,列速度表示对象的速度。如您所见,对象越来越接近该点,然后又消失了。我正在尝试使其速度曲线。我尝试了以下代码,但没有给出想要的图(因为我想显示当移动的对象靠近并超过参考点时其速度如何变化)

    ggplot(speedprofile, aes(x = distance, y = speed)) +  #speedprofile is the data frame
  geom_line(color = "red") +
  geom_smooth() + 
  geom_vline(xintercept = 0) # the vline is the reference line

情节如下:

enter image description here

然后,我尝试手动将前10个距离设置为负数,该距离在零(0)之前。所以我得到了一个更接近我想要的情节:

enter image description here

但是有一个问题。距离不能定义为负数。 综上所述,预期的情节如下(对此我很抱歉)。

enter image description here

您对如何解决此问题有任何想法吗? 先感谢您!

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作来自动计算更改点(以了解距离何时应为负),然后将轴标签设置为正。

您的数据(如果有人需要它来回答):

read.table(text="distance speed
61.0  36.4
51.4  35.3
42.2  34.2
33.4  32.8
24.9  31.3
17.5  28.4
11.5  24.1
7.1  19.4
3.3  16.9
0.5  15.5
4.4  15.1
8.5  15.5
13.1  17.3
18.8  20.5
25.7  24.1
33.3  26.3
41.0  27.0
48.7  27.7
56.6  28.4
64.8  29.2
73.6  31.7
83.3  34.2
93.4  35.3", stringsAsFactors=FALSE, header=TRUE) -> speed_profile

现在,计算“真实”距离(接近时为负,后退时为正):

speed_profile$real_distance <- c(-1, sign(diff(speed_profile$distance))) * speed_profile$distance

现在,提前计算X轴断裂:

breaks <- scales::pretty_breaks(10)(range(speed_profile$real_distance))

ggplot(speed_profile, aes(real_distance, speed)) +
  geom_smooth(linetype = "dashed") +
  geom_line(color = "#cb181d", size = 1) +
  scale_x_continuous(
    name = "distance",
    breaks = breaks,
    labels = abs(breaks) # make all the labels for the axis positive
  )

enter image description here

提供的字体在您的系统上运行良好,甚至可以:

labels <- abs(breaks)
labels[(!breaks == 0)] <- sprintf("%s\n→", labels[(!breaks == 0)])

ggplot(speed_profile, aes(real_distance, speed)) +
  geom_smooth(linetype = "dashed") +
  geom_line(color = "#cb181d", size = 1) +
  scale_x_continuous(
    name = "distance",
    breaks = breaks,
    labels = labels,
  )

enter image description here