【问题标题】:ggplotly in r generates different legend from ggplotr 中的 ggplotly 从 ggplot 生成不同的图例
【发布时间】:2020-11-03 08:41:06
【问题描述】:

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

 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

接下来我们创建如下图

  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 被渲染时,图例正确显示。当我将 p2 嵌套在 ggplotly 中时,图例变为两条黑线。

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

是否可以在p3中保留p2的图例。我请人看看

【问题讨论】:

    标签: r ggplot2 plotly legend-properties


    【解决方案1】:

    看起来ggplotly 在设置美学方面比ggplot2 更明智。只需将 fill aes 从 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"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 2020-07-10
      • 2021-12-07
      • 2023-03-17
      • 2018-08-14
      • 2020-02-25
      • 2018-04-09
      相关资源
      最近更新 更多