切割bsplines并为它们着色

时间:2018-04-09 18:32:42

标签: r ggplot2 ggforce

我对阿尔伯特·开罗的阴谋很感兴趣。

enter image description here

我可以使用ggforce :: bspline

充分平滑我的曲线

enter image description here

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

让我们假设这三个点代表1990年,1991年和1992年。并且有人在1990年7月1日当选。我想在此时改变样条的颜色。所以曲线从原点开始是红色的,直到aprox(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")

考虑到M.A.告诉我关于群组的内容,我现在可以使用以下代码:

更改直线段的颜色:

# 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"))

enter image description here

和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"))

enter image description here

或者此错误,&#34;错误:提供给离散比例的连续值&#34;用:

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手动控制离散段的颜色。

1 个答案:

答案 0 :(得分: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) 

enter image description here

修改

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

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

# 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")
)

您可以使用rainbow()这样的调色板,并指定渐变的颜色数为4,因为有四个组ABC和{ {1}}。

D

enter image description here

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

# 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之间的渐变。请注意,颜色的顺序与不同的顺序相关,导致不同的渐变,从而导致组的不同映射。

enter image description here