简体   繁体   中英

ggplot in plotly missing legend

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)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM