ggplotly 无法正确显示 geom_line [英] ggplotly not displaying geom_line correctly
问题描述
我正在尝试使用 ggplotly 为我的 ggplot 图表添加交互性.我已经尝试在 RStudio 和命令行中运行它,结果相同.
数据:
图书馆(情节)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)
如果我正常显示b
,即>b
,我得到了正确的情节
但是,如果我随后输入 ggplotly()
,我会得到下面的图:
使用我的真实数据,结果更糟.下面是一个plot()
,正确,后面是ggplotly()
知道如何正确显示吗?
虽然这是由 plotly 中的一个错误引起的(请参阅 takje 的评论),但您可以通过将您的 plot 视为不包含多个的单行来解决此错误宽度,但线段一样多,每个线段都有固定的宽度.
首先,设置数据:
库(ggplot2)图书馆(情节)set.seed(123)df1 <- as.data.frame(list('x'=1:100,'y'=1:100,'lw'=abs(rnorm(100))))
现在我们构造一个新的数据框,其中包含每条线段的起点和终点.IE.第 n 条线段从 (x_n,y_n) 到 (x_n+1, y_n+1).以下代码中的重复(
也在情节中:
ggplotly()
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
However, if I then enter ggplotly()
, I get the plot below:
Using my real data, the results are even worse. Below is a plot()
, which is correct, followed by ggplotly()
Any idea how I can display this correctly?
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 (rep) 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))
Also in plotly:
ggplotly()
这篇关于ggplotly 无法正确显示 geom_line的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!