I\'m trying to turn a ggplot into a plotly. The ggplot renders fine, but when I put it through ggplotly, suddenly the legend adds parenthesis and \",1\" after the label.
Here's a workaround that actually works:
# First, repeating your code, noting the plot as p1
# --------------------------------------------------
sorted1<-data.frame(CommDate=c(as.Date("2017-09-12"), as.Date("2017-10-15")), CommName=c("Foo", "Bar"), PubB4=c(2,3))
p1 <- ggplotly(ggplot(sorted1, aes(x=as.Date(CommDate), y=PubB4))+
geom_smooth(level=0.0, aes(colour="Moving average"), se=FALSE)+
geom_point(aes(fill=CommName), size=4)+
expand_limits(y=c(0,4.5))+
geom_line(mapping=aes(y=4),colour="orangered3",size=1)+
geom_text(mapping=aes(y=4.2, x=min(sorted1$CommDate)+4), label="Target", size=3)+
xlab("Committee Date")+
guides(fill=guide_legend(title="Committee Names"), colour=guide_legend(title.theme=element_blank(),title=NULL))+
scale_x_date(labels = date_format("%b-%y"))+
theme_light()+
theme(plot.title=element_text(hjust=0.5, size=12),panel.grid.major.x = (element_blank()),
panel.grid.minor.x = (element_blank()),
axis.title = element_text(size=8), legend.title = element_text(size=10),
legend.text = element_text(size=8), legend.box = 'vertical', legend.spacing.y = unit(-2,"mm"))+
scale_colour_manual(name="",values="#0072B2"))
Now we can proceed to the workaround:
# Now, the workaround:
# ------------------------------------------------------
p1Names <- unique(sorted1$CommName) # we need to know the "true" legend values
for (i in 1:length(p1$x$data)) { # this goes over all places where legend values are stored
n1 <- p1$x$data[[i]]$name # and this is how the value is stored in plotly
n2 <- " "
for (j in 1:length(p1Names)) {
if (grepl(x = n1, pattern = p1Names[j])) {n2 = p1Names[j]} # if the plotly legend name contains the original value, replace it with the original value
}
p1$x$data[[i]]$name <- n2 # now is the time for actual replacement
if (n2 == " ") {p1$x$data[[i]]$showlegend = FALSE} # sometimes plotly adds to the legend values that we don't want, this is how to get rid of them, too
}
p1 # now we can see the result :-)