【问题标题】:Converting ggplot to plotly - one line in different colors将ggplot转换为plotly-不同颜色的一行
【发布时间】:2017-09-10 14:44:44
【问题描述】:

我想绘制一条用不同颜色绘制的线,如下例所示:

test_data <-
    data.frame(
        var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
        var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
        date = seq(as.Date("2002-01-01"), by="1 month", length.out=100)
    )

plot <- ggplot(test_data, aes(x = date)) + 
    geom_line(aes(y = var0, group = 1, colour = c(rep(c("a", "b"), each = 25), rep("a", 50)))) + 
    geom_line(aes(y = var1, colour = "var1"))
plot

我在 plotly 或 R 中的其他一些交互式库中具有相同的绘图(以便在某些特定线/点上移动鼠标时可以显示带有一些数据的标签)。当我使用ggplotly 时,我会得到这样的结果

library(plotly)
ggplotly(plot)

你知道如何将红线和绿线组合成一行吗(在ggplot中是通过group=1参数完成的)?

【问题讨论】:

  • 为什么是colour=c(rep(c("a", "b"), each = 25), rep("a", 50)))
  • 这只是一个例子,我想要一条线有两种不同的颜色,这条线的值介于 26 和 50 之间,绿色(b 组)和所有其他红色(a 组)。这个问题的重点是如何让plotly认为这个序列应该还是一行,而不是两行。

标签: r plot ggplot2 plotly


【解决方案1】:

问题的出现是因为在第 26:50 行(大约 2004 年和 2005 年)没有“a”的数据与组分配。 ggplot force 连接点从第 25 行和第 51 行时的跳线,出现在 ggplotly 中。

这是我对长格式数据的尝试:

t2 <- test_data[26:50, ]
t2$gp <- "b"
test_data$gp <- "a"

df <- rbind(test_data, t2)
df <- gather(df, var, value, -date,  - gp)

plot <- ggplot() +
  geom_line(data=df %>% filter(var=="var0"), aes(x=date, y=value, colour=gp)) +
  geom_line(data=df %>% filter(var=="var1"), aes(x=date, y=value, colour=var))

ggplotly(plot)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 2019-05-28
    • 2023-03-24
    • 2013-08-15
    • 1970-01-01
    相关资源
    最近更新 更多