简体   繁体   中英

Add logo with ggplotly?

I am working with ggplotly as opposed to directly with plot_ly . I am trying to add a logo on the chart, following instructions found here , but nothing seems to happen.

Note : I am using ggplotly because it is easier to manipulate long axis labels in the actual data I am using.

Here is my code:

ggplotly(ggplot(mtcars) + 
           geom_point(aes(mpg, disp)),
         images = list(
           source = "https://www.rstudio.com/wp-content/uploads/2018/10/
      RStudio-Logo-Flat.png"))

I have also tried to the same effect

ggplotly(ggplot(mtcars) + 
           geom_point(aes(mpg, disp))) %>%
layout(
    images = list(
      source = "https://www.rstudio.com/wp-content/uploads/2018/10/
      RStudio-Logo-Flat.png",
      x = 0, y = 1, 
      sizex = 0.2, sizey = 0.1,
      xref = "paper", yref = "paper", 
      xanchor = "left", yanchor = "bottom"
    ),
    margin = list(t = 50)
  )

Finally, I have also tried using onRender based on an example from here :

ggplotly(ggplot(mtcars) + 
           geom_point(aes(mpg, disp))) %>%
  htmlwidgets::onRender("
function(el, x) {
// when hovering over an element, do something
el.on('plotly_hover', function(d) {
// extract tooltip text
txt = d.points[0].data.text;
// image is stored locally
image_location = 'https://www.rstudio.com/wp-content/uploads/2018/10/
      RStudio-Logo-Flat.png';
// define image to be shown
var img = {
// location of image
source: image_location,
// top-left corner
x: 1,
y: 1,
sizex: 0.2,
sizey: 0.2,
xref: 'paper',
yref: 'paper'
};
// show image and annotation
Plotly.relayout(el.id, {
images: [img]
});
})
}
")

Adding a logo in the right corner is somewhat imperative so I am hoping there is an easy fix.

You can keep a copy of the image file in www folder, say YBS.png, and then you can point to it as

layout(
    images = list(
      source = base64enc::dataURI(file = "YBS.png"),
      x = 0.9, y = 1, 
      sizex = 0.2, sizey = 0.1,
      xref = "paper", yref = "paper", 
      xanchor = "left", yanchor = "bottom"
    ))

This gives the following image:

输出

You can change the value of x between 0 and 1 to move the image to the desired location. You will need to install base64enc package.

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