How can I copy text from a single legend entry in plotly graphic?

639 views Asked by At

I'm trying to select the text of a single entry/trace from a plotly plot.

By default, text is not selectable at all from my plot, which I generated like this: In my R Markdown script, an R code chunk calls the plotly graph object. The Rmd is knitted (knitr) to HTML which I view in a browser. I could manage to make all the text selectable at once, either by

  1. supplying a text.css when knitting the Rmd containing

<style>
js-plotly-plot .plotly .user-select-none {
user-select: all !important;
}
</style>

or 2. Using this lovely bookmarklet: https://alanhogan.com/code/text-selection-bookmarklet

This is the result:

enter image description here

When dragging the cursor over the text (usual move to select text) in any line in the legend, all lines down to that line are selected at once. I would like to only have that single line selected so it can be copied easily.

I suspect this has to do with the way the legend is built in a plotly plot but I don't have enough understanding of programming to understand how to alter that. I read about plotly click events, especially 'plotly_legendclick' and 'plotly_legenddoubleclick' which do act on single line level as they enable/disable the traces in the plot: https://plotly.com/javascript/plotlyjs-events/. So possibly, some JS code could be written into the R Markdown that tackles here?

I don't understand the interaction process of knitting an R Markdown to html and JS' role (and don't know any JS). If anyone shows me a way I can provide the html file. I have run out of ideas and look forward to your suggestions. Thank you!

1

There are 1 answers

1
Kat On

There are few things that you can do.

The first—instead of making everything selectable—especially where so many pointer events exist, change the selection to only apply to the legend text.

<style>
svg g.infolayer text {
 -webkit-user-select: text;
 -moz-user-select: text;
 -ms-user-select: text;
 user-select: text;
}
</style>

The other thing that will help is removing the pointer events from the legend. By default, you can click on the legend text to hide that element from the plot. This pointer event will no doubt interfere with text selection.

You can disable this part of a Plotly graph with the following. I've added itemclick if you have traces for each legend item. I've added groupclick for if you're using legend groups.

layout(legend = list(itemclick = F, groupclick = "toggleitem"))