r - 如何绘制运动物体的速度剖面?

标签 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

您对如何解决这个问题有什么想法吗? 先感谢您!

最佳答案

您可以执行类似的操作来自动计算变化点(以了解距离何时应为负值),然后将轴标签设置为正值。

您的数据(以防有人需要它来回答):

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

关于r - 如何绘制运动物体的速度剖面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53585216/

相关文章:

python - Matplotlib 行集合和附加行

python - 将辅助数据绘制为第二个 y 轴上的刻度

r - 如何使用 R 编程发送键元素?

r - 使用 dplyr 平均排除异常值

r - 纽约数据的 tract_choropleth

iphone - 当 UIView 低于 EAGLView 时,我的性能是否会受到很大影响?

java - 在 JSOUP 中提取嵌入式资源链接的最佳方式

python - 我可以将点的颜色列表传递给 matplotlib 的 'Axes.plot()' 吗?

c++ - 在 Eclipse/StatET 中编写包含 C++ 代码的 R 包

java - 我应该从方法中抛出的异常数量是否有限制?