Home > Net >  How to insert an image above the legend in Plotly using R?
How to insert an image above the legend in Plotly using R?

Time:01-31

I have looked all around and I couldn't find any clue but layer parameter. However, layer seems to work only for the chart area, not for the legend which area is always on top of everything.

Find bellow a minimum reproducible example.

library(plotly)

x_data <- c(1, 2, 3, 4, 5)
y_data <- c(2, 3, 4, 3, 4)
labels <- c("A", "B", "C", "D", "E")

p <- plot_ly()

for (i in 1:length(x_data)) {
    p <- add_trace(p, x = x_data[i], y = y_data[i], type = 'bar', name = labels[i], legendgroup = labels[i])
}

p <- p %>% layout(margin=list(r=100))

p <- p %>% layout(legend=list(tracegroupgap=50, bgcolor="lightgrey"))

x_pos <- 1.11
y_pos <- 0.9
gap <- 0.2
images_list = list()
for (i in 1:length(x_data)) {
    if((i %% 2) == 0) {
        s <- "https://images.plot.ly/language-icons/api-home/r-logo.png?raw=true"
    } else {
        s <- "https://raw.githubusercontent.com/cldougl/plot_images/add_r_img/vox.png"
    }
    img <- list(source = s, xref = "paper", yref = "paper", x = x_pos, y = y_pos,
                sizex = 0.1, sizey = 0.1, sizing = "contain", opacity = 1, layer = "above")
    images_list[[length(images_list) 1]] <- img
    y_pos <- y_pos - gap
}

p <- p %>% layout(images=images_list)

p

The result of this code is:

Problem: Image under the legend

Desired result:

Desired result

CodePudding user response:

possibly making the legend background transparent does what you need?

if so, this does does the job:

p %>% layout(images=images_list, legend = list(bgcolor = 'rgba(0,0,0,0)'))

enter image description here

  • Related