Strange Formatting of Legend in Ggplotly in R

Strange formatting of legend in ggplotly in R

Here's yet another elegant solution. Under the hood it detects if a plotly legend name option is available and if so, removes the "(" and ",1)".

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

data = data.frame(Date=as.Date(c("2017-09-12","2017-10-15")), PubB4=c(2,3), category=c("Foo", "Bar"))

myplot = ggplotly(ggplot(data, aes(x=Date, y=PubB4))+
geom_hline(aes(yintercept=2.5, color="my line label"))+
geom_point(aes(fill=category), size=4))

for (i in 1:length(myplot$x$data)){
if (!is.null(myplot$x$data[[i]]$name)){
myplot$x$data[[i]]$name = gsub("\\(","",str_split(myplot$x$data[[i]]$name,",")[[1]][1])
}
}

myplot

plot result

Difference in legend position between ggplot and ggplotly?

Resolved pretty fast with the help of some R experts.

Added this

ggplotly(income_gap_chart) %>% layout(legend = list(orientation = "h", x = 0.4, y = -0.2))

Result:Sample Image

Thanks!



Related Topics



Leave a reply



Submit