曲线下面积 ggplotly R 未按预期呈现

Area under curve ggplotly R not rendering as per expectation

我用以下数据集和 ggplot2 创建了一个图

我从下面下载了 CSV 格式的数据集 link

https://www.kaggle.com/dataset/e392d3cfbb5749653d5c82f4bec1daa03628fb06d374fad84eac319f1b3f982422

我用过的代码如下

 library(readr)
 library(ggplot2)
 library(plotly)

接下来我从 CSV 文件创建数据框

DF <- read_csv("C:/Users/mysystem/Desktop/Random3.csv")####Please set your working directory here

现在我使用 ggplot 创建绘图

p2<-ggplot(DF, aes(x=Col1, y=Col2, group=ID)) +
 geom_line(size=.5) +  geom_ribbon(data=subset(DF, Col1>1  ),aes(x=Col1,ymax=Col2, 
fill=ID),ymin=0,alpha=0.3 ) +
scale_fill_manual(name='Legend', values=c("green4",  "red"), labels=c("A", "B" ))+labs(x="Col1", 
y="Col2")+ xlim(0, 10000)+ theme_bw()# +theme(legend.position='none') 

上图正确显示了曲线下的面积。但是,当我 运行 ggplotly 时,曲线下的面积会倒转

ggplotly(p2)

有什么办法可以避免这种情况。在某些情况下,阴影区域似乎移动到曲线下方的区域之外,在这种情况下似乎移动到曲线的反方向。我请人看一下。

我认为您只是想要 geom_area 而不是 geom_ribbon。您还可以将第一个值设置为 0 而不是跳过它,以防止生成的多边形具有反向填充。

library(ggplot2)
library(plotly)

DF <- read.csv("Random3.csv")

DF$Col2[DF$Col1 == 0] <- 0

p2 <- ggplot(DF, aes(x = Col1, y = Col2, group = ID)) +
        geom_line(size = 0.5) +  
        geom_area(aes(x = Col1, fill = ID), alpha = 0.3, 
                  position = "identity") +
        scale_fill_manual(name = 'Legend', 
                          values = c("green4", "red"), 
                          labels = c("A", "B")) + 
        labs(x = "Col1", y = "Col2") + 
        xlim(0, 10000) + 
        theme_bw()

p2 

ggplotly(p2)