Different behavior between ggplot2 and plotly using ggplotly

I want to make a line chart in plotlyso that it does not have the same color along its entire length. Color gains a continuous scale. It's easy to ggplot2, but when I translate it into plotlyusing a function ggplotly, the color defining variable behaves like a categorical variable.

require(dplyr)
require(ggplot2)
require(plotly)

df <- data_frame(
  x = 1:15,
  group = rep(c(1,2,1), each = 5),
  y = 1:15 + group
)

gg <- ggplot(df) +
  aes(x, y, col = group) +
  geom_line()

gg           # ggplot2
ggplotly(gg) # plotly

ggplot2 ( optional ): plotly : enter image description here enter image description here

I found one workaround that, on the other hand, behaves strangely in ggplot2.

df2 <- df %>% 
  tidyr::crossing(col = unique(.$group)) %>% 
  mutate(y = ifelse(group == col, y, NA)) %>% 
  arrange(col)

gg2 <- ggplot(df2) +
  aes(x, y, col = col) +
  geom_line()

gg2
ggplotly(gg2)

I also did not find a way to do this directly in plotly. Maybe there is no solution. Any ideas?

+4
source share
1 answer

, ggplotly group , . geom_segment , :

gg2 = ggplot(df, aes(x,y,colour=group)) +
  geom_segment(aes(x=x, xend=lead(x), y=y, yend=lead(y)))

gg2

enter image description here

ggplotly(gg2)

enter image description here

@rawr ( ), , group , . OP group, , .

set.seed(49)
df3 <- data_frame(
  x = 1:50,
  group = cumsum(rnorm(50)),
  y = 1:50 + group
)

gg3 geom_line, geom_point. , ggplotly . , group. geom_point, .

gg3 <- ggplot(df3, aes(x, y, colour = group)) +
  geom_point() + geom_line() +
  scale_colour_gradient2(low="red",mid="yellow",high="blue")

gg3

enter image description here

ggplotly(gg3)

enter image description here

geom_segment , ggplotly. , group ( geom_line geom_segment), , group (x, y) , :

gg4 <- ggplot(df3, aes(x, y, colour = group)) +
  geom_segment(aes(x=x, xend=lead(x), y=y, yend=lead(y))) +
  scale_colour_gradient2(low="red",mid="yellow",high="blue")

ggplotly(gg4)

enter image description here

+3

Source: https://habr.com/ru/post/1664470/


All Articles