Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

r - ggplotly not displaying geom_line correctly

I am trying to use ggplotly to add interactivity to my ggplot chart. I have tried running this in both RStudio and from the command line, with the same results.

Data:

library(plotly)
df1 <- as.data.frame(list('x'=1:100,'y'=1:100,'lw'=abs(rnorm(100))))
b <- ggplot(data=df1, aes(x=x,y=y)) + geom_line(size=df1$lw)

If I display b normally, i.e. > b, I get a correct plot enter image description here

However, if I then enter ggplotly(), I get the plot below: enter image description here

Using my real data, the results are even worse. Below is a plot(), which is correct, followed by ggplotly() enter image description here

enter image description here

Any idea how I can display this correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Although this is caused by a bug in plotly (see comment from takje), you can work around this bug by treating your plot not as a single line with multiple widths, but as many line segments, each with a fixed width.

First, set up the data:

library(ggplot2)
library(plotly)
set.seed(123)
df1 <- as.data.frame(list('x'=1:100,'y'=1:100,'lw'=abs(rnorm(100))))

Now we construct a new data frame that contains the start and end points of each line segment. I.e. nth line segment goes from (x_n,y_n) to (x_n+1, y_n+1). The repetition () in the following code is because intermediate points form the endpoint of one segment, and also the start-point of the next. The first and last points of the whole set are not repeated because they appear only in a single line segment:

x2 <- c(df1$x[1], rep(df1$x[2:(NROW(df1)-1)], each=2),  df1$x[NROW(df1)])
y2 <- c(df1$y[1], rep(df1$y[2:(NROW(df1)-1)], each=2),  df1$y[NROW(df1)])
df2 <- data.frame(x2,y2)

Next, we label each of the x, and y coordinates with a segnum label, that refers to which line segment they are in:

df2$segnum <- rep(1:(NROW(df1)-1), each=2)

and another vector that corresponds to these segment numbers, and contains the line width for each segment:

df2$segw <- rep(df1$lw[1:(NROW(df1)-1)], each=2)

and plot:

ggplot(data=df2, aes(x=x2,y=y2, colour=segnum)) + geom_line(aes(group = segnum, size=segw))

enter image description here

Also in plotly:

ggplotly()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...