djc55
djc55

Reputation: 555

Reducing space between y-axis and plot title/axis ticks

I am outputting a scatterplot in R using plotly with the code below:

library(tidyverse)
library(plotly)

set.seed(1)

data.frame(state = c(rep(state.name, 2)),
           value = sample(1:100, 100)) %>% 
  plot_ly(x = ~value,
          y = ~state,
          type = "scatter",
          mode = "markers") %>% 
  layout(title = list(text = "State Information"))

The issue that I am running into is that the code above renders a plot with an excessive amount of space between the y-axis and the plot title and x-axis ticks respectively:

enter image description here

Can anyone tell me how I can shrink this space so that the plot margins are tighter?

Edit: I know that a similar question was asked here, but this relates to a numeric y-axis, not a categorical one:

R Plotly - Large unused space on top and bottom of graph when setting height

Upvotes: 1

Views: 1114

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33417

We can use the same procedure for a categorical axis.

Please run schema() and navigate: object ► layout ► layoutAttributes ► yaxis ► range:

[...] If the axis type is category, it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears.

library(plotly)
library(datasets)

set.seed(1)

DF <- data.frame(state = c(rep(state.name, 2)),
                 value = sample(1:100, 100))

plot_ly(
  data = DF,
  x = ~ value,
  y = ~ state,
  type = "scatter",
  mode = "markers"
) %>%
  layout(
    title = list(text = "State Information"),
    xaxis = list(
      range = ~ c(-1, length(unique(value)) + 1)
    ),
    yaxis = list(
      range = ~ c(-1, length(unique(state))),
      title = list(text = "state", standoff = 0L)) # maybe needed? sets distance between title and labels
  )

result

Upvotes: 1

Related Questions