I am having trouble getting a legend to show up in plotly, specifically with ggplot + geom_line
.
I am using plotly 3.6.0
and ggplot2 2.1.0
To demonstrate my problem I'll build a simple data frame:
x = 1:5
y1 = 1:5
y2 = y1 * 2
d = data.frame(x, y1, y2)
g = ggplot(data = d, aes(x=x)) +
geom_line(aes(y = y1, col = 'y1')) +
geom_line(aes(y = y2, col = 'y2')) +
scale_color_manual(values = c('red', 'blue'), labels = c('y1 lab', 'y2 lab'), name = '')
g
This creates a ggplot figure with a legend. However, when I attempt to create an interactive version using plotly the legend is no longer there.
ggplotly(g)
I attempted the following to solve the problem:
g_build = plotly_build(g)
g_build$layout$showlegend <- TRUE
g_build$layout$margin <- list(l=80, r=300, b=80, t=100, pad=0)
g_build
library(reshape2)
d<-melt(d,id="x")
g <- ggplot(data = d, aes(x=x, y=value, color=variable)) +
geom_line() +scale_color_manual(values = c('red', 'blue'),
labels = c('y1 lab', 'y2 lab'), name = '')
ggplotly(g)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With