繁体   English   中英

r 中的 ggplotly 生成与 ggplot 不同的图例

[英]ggplotly in r generates different legend from ggplot

我在 R 中创建了以下 dataframe。 第一步是导入必要的库

 library(ggplot2)
 library(plotly)
 library(dplyr)

我们在这里创建dataframe如下

  DF_1<-data.frame("A"= c(1:10))
  DF_1$B<-c("D", "C")
  DF_1$C<-DF_1$A^2

接下来我们创建一个plot如下

  p2<-ggplot(DF_1, aes(x=A, y=C, group=B, fill=B)) +
  geom_line(size=.5) +  geom_ribbon(data=subset(DF_1),aes(x=A,ymax=C),ymin=0,alpha=0.3) +
  scale_fill_manual(name='Legend', values=c("green4",  "red"), labels=c("D", "C" ))+theme_bw() 

渲染 p2 时,图例会正确显示。 当我在 ggplotly 中嵌套 p2 时,图例变为两条黑线。

   p3<-ggplotly(p2, dynamicTicks = T)
   p3= layout(p3, xaxis = list(type = "log"))

是否可以在p3中保留p2的传说? 我请人看看

看起来ggplotly在如何设置美学方面比ggplot2更明智。 只需将fill aes 从 ggplot 中的全局设置移动到ggplot geom_ribbon给出正确的图例:

library(ggplot2)
library(plotly)
library(dplyr)

DF_1<-data.frame("A"= c(1:10))
DF_1$B<-c("D", "C")
DF_1$C<-DF_1$A^2

ggplot(DF_1, aes(x = A, y = C, group=B)) +
  geom_line(size=.5) + 
  geom_ribbon(aes(x = A, ymin = 0, ymax = C, fill = B), alpha=0.3) +
  scale_fill_manual(name='Legend', values=c("green4",  "red"), labels=c("D", "C" ))+theme_bw() 

ggplotly(dynamicTicks = T) %>% 
  layout(xaxis = list(type = "log"))

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM