Raghavan vmvs
Raghavan vmvs

Reputation: 1265

ggplotly in r generates different legend from ggplot

I have created the following dataframe in R. The first step is to import the necessary libraries

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

We create the dataframe here as follows

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

Next we create a plot as follows

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

When p2 is rendered, the legend displays correctly. When I nest p2 in ggplotly, the legend changes to two dark lines.

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

Is it possible to retain the legends of p2 in p3. I request someone to take a look

Upvotes: 1

Views: 966

Answers (1)

stefan
stefan

Reputation: 123783

Looks like ggplotly is a more sensible than ggplot2 in how one sets the aesthetics. Simply moving the fill aes from the global setup in ggplot into geom_ribbon gives the correct legend:

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"))

enter image description here

Upvotes: 1

Related Questions