Уменьшите количество линий сетки на графиках точечного разброса с логарифмическим масштабом в R блестящий - PullRequest
0 голосов
/ 10 февраля 2019

Я построил следующее тестовое приложение, в котором я решил проблему, чтобы получить метки тиков в качестве научной аннотации, но теперь я хотел бы уменьшить количество линий сетки, которые будут размещаться только на «основных» тиках, т.е.те, которые имеют текстовую метку.Этот вопрос был опубликован на основе обсуждения / комментария к предыдущему SO вопросу

Я хотел бы найти способ, который работает как для 2D, так и для 3D графиков с точечной диаграммой, так как я использую оба.

Вот 3D-приложение.

    library(shiny)
    library(plotly)

    shinyApp(
      ui = fluidPage( plotlyOutput('plot') ),

      server = function(input, output) {
        output$plot <- renderPlotly ({

          mtcars <- rbind(mtcars, mtcars*1000, mtcars/1000)  #create data with big logarithmic range
          maxlog <- round(log10(max(mtcars[['mpg']][mtcars[['mpg']]>0], mtcars[['disp']][mtcars[['disp']]>0],mtcars[['cyl']][mtcars[['cyl']]>0])), digits = 0) +1 # determine max log needed
          minlog <- round(log10(min(mtcars[['mpg']][mtcars[['mpg']]>0], mtcars[['disp']][mtcars[['disp']]>0],mtcars[['cyl']][mtcars[['cyl']]>0])), digits = 0) -1 # determine min log needed
          logrange <- (maxlog - minlog)*9 +1 # get the distance between smallest and largest log power
          tval <- sort(as.vector(sapply(seq(1,9), function(x) x*10^seq(minlog, maxlog)))) #generates a sequence of numbers in logarithmic divisions
          ttxt <- rep("",length(tval))  # no label at most of the ticks
          ttxt[seq(1,logrange,9)] <- formatC(tval, format = "e", digits = 2)[seq(1,logrange,9)] # every 9th tick is labelled


          p <- plot_ly(source = 'ThresholdScatter')
          p <- add_trace(p, data = mtcars, 
                      x = mtcars[['mpg']], 
                      y = mtcars[['disp']],
                      z = mtcars[['cyl']],
                      type = 'scatter3d', 
                      mode = 'markers',
                      marker = list(size = 2)) 

      p <- layout(p, autosize = F, width = 500, height = 500,
                  scene = list(yaxis = list(type="log",
                                            zeroline=F, showline=T, 
                                            ticks="outside",
                                            tickvals=tval,
                                            ticktext=ttxt),
                               xaxis = list(type="log",
                                            zeroline=F, showline=T, 
                                            ticks="outside",
                                            tickvals=tval,
                                            ticktext=ttxt),
                               zaxis = list(type="log",
                                            zeroline=F, showline=T, 
                                            ticks="outside",
                                            tickvals=tval,
                                            ticktext=ttxt),
                               camera = list(eye = list(x = -1.5, y = 1.5, z = 1.5))))
    })
  }
    )

и то же самое, но в 2D

        library(shiny)
        library(plotly)

        shinyApp(
          ui = fluidPage( plotlyOutput('plot') ),

          server = function(input, output) {
            output$plot <- renderPlotly ({

                  mtcars <- rbind(mtcars, mtcars*1000, mtcars/1000)  #create data with big logarithmic range
                  maxlog <- round(log10(max(mtcars[['mpg']][mtcars[['mpg']]>0], mtcars[['disp']][mtcars[['disp']]>0])), digits = 0) +1 # determine max log needed
                  minlog <- round(log10(min(mtcars[['mpg']][mtcars[['mpg']]>0], mtcars[['disp']][mtcars[['disp']]>0])), digits = 0) -1 # determine min log needed
                  logrange <- (maxlog - minlog)*9 +1 # get the distance between smallest and largest log power
                  tval <- sort(as.vector(sapply(seq(1,9), function(x) x*10^seq(minlog, 

    maxlog)))) #generates a sequence of numbers in logarithmic divisions
              ttxt <- rep("",length(tval))  # no label at most of the ticks
              ttxt[seq(1,logrange,9)] <- formatC(tval, format = "e", digits = 2)[seq(1,logrange,9)] # every 9th tick is labelled


              p <- plot_ly(source = 'ThresholdScatter')
              p <- add_trace(p, data = mtcars, 
                             x = mtcars[['mpg']], 
                             y = mtcars[['disp']],
                             type = 'scatter', 
                             mode = 'markers',
                             marker = list(size = 2)) 

              p <- layout(p,autosize = F, width = 500, height = 500,
                          yaxis = list(type="log",
                                         zeroline=F, showline=T, 
                                         ticks="outside",
                                         tickvals=tval,
                                         ticktext=ttxt),
                          xaxis = list(type="log",
                                       zeroline=F, showline=T, 
                                       ticks="outside",
                                       tickvals=tval,
                                       ticktext=ttxt))
            })
          }


  )

Ответы [ 2 ]

0 голосов
/ 01 апреля 2019

В Python для трехмерного графика укажите все атрибуты Layout в пределах scene dict следующим образом:

layout = go.Layout(
        margin=dict(
        l=0,
        r=0,
        b=0,
        t=0
    ),
    scene=dict(
    xaxis=dict(
        type='log',
               autorange=True,
               title='L1'))
)

Я бы предположил, что такая же функциональность существует в R для последней версии plotly.

enter image description here

0 голосов
/ 10 февраля 2019

Для 2D точечной диаграммы вы можете нарисовать свои собственные линии сетки, используя опцию shapes в layout.Затем вы также подавляете линии сетки, используя showgrid = FALSE.

shinyApp(
  ui = fluidPage( plotlyOutput('plot') ),

  server = function(input, output) {

    hline <- function(y = 0, color = "grey", width=0.1) {
      list(type = "line", x0 = 0, x1 = 1, xref = "paper",
        y0 = y, y1 = y, line = list(color = color, width=width))
    }

    output$plot <- renderPlotly ({
      mtcars <- rbind(mtcars, mtcars*1000, mtcars/1000)  #create data with big logarithmic range
      maxlog <- round(log10(max(mtcars[['mpg']][mtcars[['mpg']]>0], mtcars[['disp']][mtcars[['disp']]>0])), digits = 0) +1 # determine max log needed
      minlog <- round(log10(min(mtcars[['mpg']][mtcars[['mpg']]>0], mtcars[['disp']][mtcars[['disp']]>0])), digits = 0) -1 # determine min log needed
      logrange <- (maxlog - minlog)*9 +1 # get the distance between smallest and largest log power
      tval <- sort(as.vector(sapply(seq(1,9), function(x) x*10^seq(minlog, 

        maxlog)))) #generates a sequence of numbers in logarithmic divisions
      ttxt <- rep("",length(tval))  # no label at most of the ticks
      ttxt[seq(1,logrange,9)] <- formatC(tval, format = "e", digits = 2)[seq(1,logrange,9)] # every 9th tick is labelled

      p <- plot_ly(source = 'ThresholdScatter')
      p <- add_trace(p, data = mtcars, 
        x = mtcars[['mpg']], 
        y = mtcars[['disp']],
        type = 'scatter', 
        mode = 'markers',
        marker = list(size = 2)) 

      p <- layout(p,autosize = F, width = 500, height = 500,
        yaxis = list(type="log",
          zeroline=F, showline=T, showgrid=F,
          ticks="outside",
          tickvals=tval,
          ticktext=ttxt),
        xaxis = list(type="log",
          zeroline=F, showline=T, showgrid=F,
          ticks="outside",
          tickvals=tval,
          ticktext=ttxt),
        shapes = lapply(10^(-1:6), hline))
    })
  }
)

enter image description here

К сожалению, я не думаю, что вы можете использовать этот подход в 3Dграфик, так как фигуры не имеют размерности z.Вы можете сделать что-то подобное, используя add_lines вместо фигур, но это будет не так аккуратно.

...