将ggplot转换为plotly-一行不同的颜色 [英] Converting ggplot to plotly - one line in different colors

查看:185
本文介绍了将ggplot转换为plotly-一行不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to have plot where one line in drawn in different colors as in example below:

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

在R中的绘图或其他交互式库中要具有相同的绘图(以便在将鼠标移到某些特定的线/点上时可以显示带有某些数据的标签).当我使用ggplotly时,我会得到类似的东西

I what to have the same plot in plotly or some other interactive library in R (so that the lables with some data could be displayed when moving the mouse on some specific line/point). When I use ggplotly I get something like this

library(plotly)
ggplotly(plot)

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

Do you know how to combine red and green line in one line (in ggplot it is done through group=1 parameter)?

推荐答案

之所以出现此问题,是因为没有26:50行(与2004年和2005年左右)的"a"数据与组分配有关.当ggplot强制从第25行和第51行连接点时,该行跳到ggplotly中.

The issue arises as there's no data for "a" for lines 26:50 (around 2004 and 2005) with the group assignment. The line jump when ggplot force join points from line 25 and line 51, which appear in ggplotly.

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

Here's my attempt with a long form of data:

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)

这篇关于将ggplot转换为plotly-一行不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆