首页 > 解决方案 > R意大利面条图 - 用连接点改变线条颜色

问题描述

带有 geom_line 和 geom_smooth 的意大利面条图。我必须根据“”绘制“ f0time_steps,线条根据“”因子改变颜色,part而不会在其两个级别“ os”和“ fv”之间断开连接。当“ part”变化时,平滑也会消失。

我的数据集的结构:

structure(list(time_steps = 1:20, f0.2 = c(203.61, 204.62, 204.23, 
207.71, 198.5, 184.43, 185.15, 182.13, 183.2, 189.47, 188.88, 
188.43, 188.53, 189.41, 191.15, 193.76, 196.6, 199.44, 201.45, 
202.53), part = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("os", 
"fv"), class = "factor")), row.names = c(NA, -20L), class = "data.frame")

我写的代码:

ggplot (df, aes(time_steps, f0, colour = (part))) +
  geom_line(alpha = 0.1) + geom_smooth(size = 2)

我用断开的线得到的情节:

这里

有人有解决这个问题的建议吗?

标签: r

解决方案


除非 part 的两个值之间存在共同点,否则按颜色打破线图将始终留下间隙。该差距表示没有 for 的值,也没有time_steps > 10for的part == "os"值。time_steps < 12part == "fv"

使用一些看起来像你的模拟数据,这是一个解决方法。它涉及使用geom_line两次,一次没有颜色美学映射,因此您可以连接点。然后我使用stat_smooth()了两次(一次用于线条,一次用于功能区),因为它可以更好地控制绘图的外观。

df <- data.frame(time_steps = 1:20,
                 f0 = round(runif(20, 190, 210)),
                 part = c(rep("os", 10), rep("fv", 10)))

ggplot(df) +
   geom_line(aes(x = time_steps, y = f0), color = "black", size = 1.5, alpha = 0.5) +
   geom_line(aes(x = time_steps, y = f0, color = part), size = 1.5, alpha = 1) +
   stat_smooth(geom ='line', aes(x = time_steps, y = f0), color = "black", size = 1.5, linetype = 2, alpha=0.5) + 
   stat_smooth(geom = 'ribbon', aes(x = time_steps, y = f0), color = "NA", fill = "black", alpha = 0.1)

试图绘制 OP 想要什么


推荐阅读