简体   繁体   中英

Different behavior between ggplot2 and plotly using ggplotly

I want to make a line chart in plotly so that it does not have the same color on its whole length. The color is given continuous scale. It is easy in ggplot2 but when I translate it to plotly using ggplotly function the variable determining color behaves like 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 (desired): 在此处输入图片说明 plotly : 在此处输入图片说明

I found one work-around that, on the other hand, behaves oddly 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 how to do this in plotly directly. Maybe there is no solution at all. Any ideas?

It looks like ggplotly is treating group as a factor, even though it's numeric. You could use geom_segment as a workaround to ensure that segments are drawn between each pair of points:

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

gg2

在此处输入图片说明

ggplotly(gg2)

在此处输入图片说明

Regarding @rawr's (now deleted) comment, I think it would make sense to have group be continuous if you want to map line color to a continuous variable. Below is an extension of the OP's example to a group column that's continuous, rather than having just two discrete categories.

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

Plot gg3 below uses geom_line , but I've also included geom_point . You can see that ggplotly is plotting the points. However, there are no lines, because no two points have the same value of group . If we hadn't included geom_point , the graph would be blank.

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

gg3

在此处输入图片说明

ggplotly(gg3)

在此处输入图片说明

Switching to geom_segment gives us the lines we want with ggplotly . Note, however, that line color will be based on the value of group at the first point in the segment (whether using geom_line or geom_segment ), so there might be cases where you want to interpolate the value of group between each (x,y) pair in order to get smoother color gradations:

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM