Download data from plotly graph

I have a plotly graph, and would like to download the data.

  • Option 1 is a download button outside the graph to a data object (e.g CSV, or a table). For example
    Download output file csv. It works, but not that neat.

Options 2 and 3 use a custom modebar button.
plotly book - custom modebar button has a nice example with code to make the custom button.

  • Option 2, is a download button (eg csv) as a plotly custom modebar button. Presumably this would be done in javascript and passed through, similar to example below in option 3? Suggestions for how to do this?

  • Option 3 is a button that links to a table (possibly an appendix or other website with a datatable object), where that datatable has a download button. The download button for datatable is easy (see here). The javascript code for a website link should look something like this (javascript link to website)
    Am I missing something simple in this code?

#devtools::install_github('cpsievert/plotly_book') #for octocat image
library(tidyverse)
library(DT)
library(plotly)

data(octocat_svg_path, package = "plotlyBook")
  
octocat <- list(
    name = "octocat",
    icon = list(
      path = octocat_svg_path,
      transform = 'matrix(1 0 0 1 -2 -2) scale(0.7)'
    ),
    click = htmlwidgets::JS(
      "function(gd) {window.location.href = 'http://www.google.com';
    }"
    )
  )
plot_ly() %>%
    config(modeBarButtonsToAdd = list(octocat))

*edited to include code for making octocat image available

1 Like

Check out this post.

Could be part of the solution, but not sure how to wrap that output option into a csv download command that is included into the “click” code.

This is the javascript you need. It builds a string from the data in the plot traces, then exports this to a file as a blob. I don't think it's possible to retrieve the original dataframe.

function(gd) {
            var text = '';
            for(var i = 0; i < gd.data.length; i++){
              text += gd.layout.xaxis.title.text + gd.data[i].name + ',' + gd.data[i].x + '\\n';
              text += gd.layout.yaxis.title.text + gd.data[i].name + ',' + gd.data[i].y + '\\n';
            };
            var blob = new Blob([text], {type: 'text/plain'});
            var a = document.createElement('a');
            const object_URL = URL.createObjectURL(blob);
            a.href = object_URL;
            a.download = 'data.csv';
            document.body.appendChild(a);
            a.click();
            URL.revokeObjectURL(object_URL);
          }
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.