ggplotly无法正确显示geom_line [英] ggplotly not displaying geom_line correctly

查看:418
本文介绍了ggplotly无法正确显示geom_line的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用ggplotly为我的ggplot图表添加交互性。我已经尝试在RStudio和命令行中运行这个,结果相同。



数据:

<$ (列表)('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()





任何想法如何正确显示这一点?

解决方案

尽管这是由于一个错误导致的(请参阅takje的评论),你可以通过把你的情节看作不是多条宽度的单行,而是多条线段,每条都有一个固定的宽度来解决这个问题。

首先,设置数据:

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

现在我们构造一个新的数据框,其中包含每个线段的起点和终点。即第n条线段从(x_n,y_n)变为(x_n + 1,y_n + 1)。以下代码中的重复( <

$ p
$ b $ p














$ b


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 () 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆