0

我对阿尔伯特开罗的这个情节很感兴趣。

在此处输入图像描述

我可以用 ggforce::bspline 充分平滑我的曲线

在此处输入图像描述

但是,既然我没有日期轴,我不确定如何在中途更改样条曲线的颜色。

Let's assume that the three points represent the years 1990, 1991 and 1992. And someone got elected on July 1, 1990. I would like to change the color of the spline at this point. 所以曲线从原点到近似 (12, 5.6) 是红色的,然后从 (12, 5.6) 到 (17,4) 是蓝色的

我不知道如何做到这一点。

library(ggforce)
library(ggplot2)

data <- tibble (
  x = c(10, 15, 17),
  y = c(5, 7, 4)
)

ggplot(data) + 
  stat_bspline2(aes(x = x, y = y), n = 300,  geom = "bspline0", color = "red") +
  stat_bspline2(aes(x = x, y = y), n = 3,  geom = "point", color = "red") +
  geom_point(aes(x = x, y = y), color = "grey")

想想 MA 告诉我的关于组的内容,我现在拥有的代码可以:

改变直线段的颜色:

# Works for straight lines
ggplot(data, aes(x=x, y=y, colour = g, group = 1)) + 
  geom_line(size = 3) + 
  geom_point() +
  scale_color_manual(values = c("A" = "red", "B" = "pink", "C" = "green", "D" = "white"))

在此处输入图像描述

以及 bspline 的连续颜色。但我希望这只是上图中的离散颜色。

# Works with continuous color
ggplot(data, aes(x=x, y=y, colour = g, group = 1)) + 
  geom_bspline2(size = 4, n = 300) +
  scale_color_manual(values = c("A" = "red", "B" = "pink", "C" = "green", "D" = "white"))

在此处输入图像描述

或者这个错误,“错误:提供给离散比例的连续值”:

ggplot(data) + 
  stat_bspline2(aes(x = x, y = y, color = ..group.., group = 1), n = 300,  geom = "bspline0") +
  scale_color_manual(values = c("A" = "red", "B" = "pink", "C" = "green", "D" = "white"))

所以我想知道如何使用 bspline 手动控制离散段的颜色。

4

1 回答 1

2

您可以通过分组来做到这一点:

data <- tibble (
  x = c(10, 15, 17, 17, 20, 22),
  y = c(5, 7, 4, 4, 0, 5),
  g = c("A", "A", "A", "B", "B", "B")
)

ggplot(data) + 
  stat_bspline2(
                aes(x = x, y = y, color = ..group.., group = g), 
                n = 300,  geom = "bspline0") +
  scale_colour_gradient(low = "blue", high = "red", guide=FALSE) 

在此处输入图像描述

编辑:

这个错误Continuous value supplied to discrete scale在这里有点令人困惑。我不知道是否有更简单的方法来获得您想要的,但可以使用scale_colour_gradientn(). 此功能允许将组映射到颜色g之间的渐变,因此您想要成为组的数量。nn

例如,考虑一个包含四组的更大数据集:

# example data
data <- tibble (
  x = c(10, 15, 17, 17, 20, 22, 22, 23, 25, 25, 27, 29),
  y = c(5, 7, 4, 4, 0, 5, 5, 6, 5, 5, 4, 5.5),
  g = c("A", "A", "A", "B", "B", "B", "C", "C", "C", "D","D","D")
)

您可以使用调色板,并将渐变的颜色数指定为 4 ,rainbow()因为有四个组A、和。BCD

# use a colour palette:
ggplot(data) + 
  stat_bspline2(
    aes(x = x, y = y, color = ..group.., group = g), 
    n = 300, size = 1,  geom = "bspline0") +
    scale_color_gradientn(colours = rainbow(4), 
                          guide = F
                          )

在此处输入图像描述

对于自定义颜色,您可以执行以下操作:

# use custom colors:
ggplot(data, aes(x=x, y=y, color = ..group.., group = g)) + 
  geom_bspline2(size = 1, n = 300) +
  scale_color_gradientn(
    colours = c("red", "pink", "green", "white"),
    guide = F
    )

这使用颜色redpinkgreen之间的渐变white。请注意,颜色的顺序很重要,因为不同的顺序会导致不同的渐变,从而导致组的不同映射。

在此处输入图像描述

于 2018-04-09T20:42:26.090 回答