在颠簸图中使用曲线

在颠簸图中使用曲线

本文介绍了在颠簸图中使用曲线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作颠簸图(例如平行坐标,但要使用序数x轴)以显示随时间变化的排名.我可以很容易地制作一条直线图:

I'm trying to make a bumps chart (like parallel coordinates but with an ordinal x-axis) to show ranking over time. I can make a straight-line chart very easily:

library(ggplot2)
set.seed(47)

df <- as.data.frame(as.table(replicate(8, sample(4))), responseName = 'rank')
df$Var2 <- as.integer(df$Var2)

head(df)
#>   Var1 Var2 rank
#> 1    A    1    4
#> 2    B    1    2
#> 3    C    1    3
#> 4    D    1    1
#> 5    A    2    3
#> 6    B    2    4

ggplot(df, aes(Var2, rank, color = Var1)) + geom_line() + geom_point()

很棒.但是,现在,我想使连接线弯曲.尽管x永远不会超过y,但geom_smooth提供了一些可能性. loess似乎应该起作用,因为它可以忽略除最接近点以外的点.但是,即使进行了最佳调整,我仍然可以错过很多点,并超出其他应该保持平坦的点:

Wonderful. Now, though, I want to make the connecting lines curved. Despite never having more than one y per x, geom_smooth offers some possibilities. loess seems like it should work, as it can ignore points except the closest. However, even with tweaking the best I can get still misses lots of points and overshoots others where it should be flat:

ggplot(df, aes(Var2, rank, color = Var1)) +
    geom_smooth(method = 'loess', span = .7, se = FALSE) +
    geom_point()

我尝试了许多其他样条线,例如ggalt::geom_xspline,但是它们都仍然过冲或错过了要点:

I've tried a number of other splines, like ggalt::geom_xspline, but they all still overshoot or miss the points:

ggplot(df, aes(Var2, rank, color = Var1)) + ggalt::geom_xspline() + geom_point()

是否有简单的方法可以弯曲这些线?我需要建立自己的S形样条吗?为了澄清,我正在寻找类似 D3.js的d3.curveMonotoneX 命中每个点,并且其局部最大值和最小值不超过y值:

Is there an easy way to curve these lines? Do I need to build my own sigmoidal spline? To clarify, I'm looking for something like D3.js's d3.curveMonotoneX which hits every point and whose local maxima and minima do not exceed the y values:

理想情况下,每个点的斜率也可能为0,但这并不是绝对必要的.

Ideally it would probably have a slope of 0 at each point, too, but that's not absolutely necessary.

推荐答案

signal::pchip与X值网格配合使用是有效的,至少在您的示例中为数字轴.适当的geom_会很好,但嘿...

Using signal::pchip with a grid of X-values works, at least in your example with numeric axes. A proper geom_ would be nice, but hey...

library(tidyverse)
library(signal)
set.seed(47)

df <- as.data.frame(as.table(replicate(8, sample(4))), responseName = 'rank')
df$Var2 <- as.integer(df$Var2)

head(df)
#>   Var1 Var2 rank
#> 1    A    1    4
#> 2    B    1    2
#> 3    C    1    3
#> 4    D    1    1
#> 5    A    2    3
#> 6    B    2    4

ggplot(df, aes(Var2, rank, color = Var1)) +
  geom_line(data = df %>%
              group_by(Var1) %>%
              do({
                tibble(Var2 = seq(min(.$Var2), max(.$Var2),length.out=100),
                       rank = pchip(.$Var2, .$rank, Var2))
              })) +
  geom_point()

结果:

这篇关于在颠簸图中使用曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:37