r - ggplotly 未正确显示 geom_line

标签 r plot ggplot2 plotly

我正在尝试使用 ggplotly 为我的 ggplot 图表添加交互性。我尝试在 RStudio 和命令行中运行它,得到相同的结果。

数据:

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)

如果我正常显示 b,即 > b,我会得到正确的绘图 enter image description here

但是,如果我输入ggplotly(),我会得到下面的图: enter image description here

使用我的真实数据,结果更糟。下面是一个 plot(),这是正确的,后面是 ggplotly() enter image description here

enter image description here

知道如何正确显示它吗?

最佳答案

虽然这是由plotly中的错误引起的(请参阅 takje 的评论),但您可以通过将绘图视为多个线段(每个线段具有固定宽度)来解决此错误,而不是将绘图视为具有多个宽度的单线。

首先,设置数据:

library(ggplot2)
library(plotly)
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)。以下代码中的重复( )是因为中间点形成一个线段的端点,也是下一个线段的起点。整个集合的第一个和最后一个点不会重复,因为它们仅出现在单个线段中:

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)

接下来,我们用 segnum 标签标记每个 x 和 y 坐标,该标签指的是它们所在的线段:

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

以及与这些段编号相对应的另一个向量,并包含每个段的线宽:

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

和 plotly :

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

enter image description here

也在 plotly 中:

ggplotly()

enter image description here

关于r - ggplotly 未正确显示 geom_line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36757441/

相关文章:

image - OSX 中的 tiff() 分辨率和压缩设置不可靠

r - 在顶层 : 'README.Rmd' persists even after implementing suggested solutions 发现非标准文件/目录

r - ggplot2 中两个不同组的不同调色板

r - 使用 ggfortify 和 ggrepel 进行 PCA

r - 如何使用 gganimate 对 geom_bar/geom_col 的移动填充部分进行动画处理?

r - 使用 rbind() 在 lapply() 中将多个数据帧组合成一个更大的 data.frame

r - 如何在 R 中绘制条形图?

r - ggplot2:qplot 面轴自由缩放,同时保留网格

python - 用垂直线绘制 pandas 数据框

r - 带有 stat_binhex 的 map 上的六边形热图给出错误 : geom_hex() only works with Cartesian coordinates