Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot in plotly missing legend

Tags:

r

ggplot2

plotly

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
like image 528
Alejandro Sotolongo Avatar asked Oct 18 '22 01:10

Alejandro Sotolongo


1 Answers

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)

enter image description here

like image 147
Cyrus Mohammadian Avatar answered Oct 31 '22 12:10

Cyrus Mohammadian