Changing line thickness and opacity in scatterplot on onRender() htmlWidgets in R

我的梦境 提交于 2019-12-20 06:32:31

问题


I am hoping to make a plot using the R package htmlwidgets' onRender() function in which a user can click on a point and a line is drawn. I have the crux of it working right now where a gray line is drawn at its default thickness and probably its default opaqueness.

However, I have been stuck on changing the thickness of the line (and possibly changing the opaqueness of the line, although it may be working and I cannot see it since the line is so thin). I want the line to be very thick and rather transparent. I tried several parameters and approaches for line width and opaqueness (some of which are commented out below), but it seems they do not make a difference. Any ideas what I may be missing? Thank you.

library(plotly)
library(broom)

dat <- mtcars
dat$mpg <- dat$mpg * 10

p <- ggplot(data = dat, aes(x=disp,y=mpg)) + geom_point(size=0.5)

ggplotly(p) %>%
  onRender("
           function(el, x, data) {
            // reduce the opacity of every trace except for the hover one
            el.on('plotly_click', function(e) {

              var trace1 = {
                 x: [100, 400],
                 y: [100, 400],
                 mode: 'lines',
                 //line: dict(color: 'gray', width: 100)
                 marker: {
                   color: 'gray',
                   size: 200,
                   width: 1000,
                   opacity: 0.5
                 }
              }
              Plotly.addTraces(el.id, trace1);
           })
          }
          ", data=dat)

回答1:


The opacity would need to be in the trace object. Your line object has some syntax issues which prevents Javascript from reading it.

gp %>% onRender("
function(el, x, data) {

  el.on('plotly_click', function(e) {

  var trace1 = {
    x: [100, 400],
    y: [100, 400],
    mode: 'lines',
    line: {
        color: 'gray', 
        width: 100
    },
    opacity: 0.8,
  }
  Plotly.addTraces(el.id, trace1);
})
}", data=dat)


来源:https://stackoverflow.com/questions/42541129/changing-line-thickness-and-opacity-in-scatterplot-on-onrender-htmlwidgets-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!