Home > OS >  Bar plot does not render in horizontal orientation
Bar plot does not render in horizontal orientation

Time:11-09

I have dataset of companies and counts that I would like to render as a horizontal bar plot:

       name        count
    1  Company1     7067
    2  Company2      810
    3  Company3     9524
    4  Company4     2878
    5  Company5     4014
    6  Company6     6565
    7  Company7      772
    8  Company8     4810
    9  Company9      785
    10 Company10    1330

For this purpose I have following piece of code:

data %>%
plot_ly(
    x = ~name,
    y = ~count,
    marker = list(color = colors[1]),
    type = 'bar',
    orientation = 'h'
    ) %>%
  layout(
    paper_bgcolor = "#F5F5F5",
    plot_bgcolor = "#F5F5F5",
    xaxis = list(
      title = "company",
      categoryorder = "total descending"
    ),
    yaxis = list(
      title = "count"
    )
  )

The code works well until I add orientation = 'h' line. Then it does not throw any error but it renders blank (empty chart). Is there anything that does not fit together with the horizontal orientation?

CodePudding user response:

The issue is that you mapped the categorical column on x and the numeric on y. Simply switch that and you are fine

library(plotly)

data %>%
  plot_ly(
    y = ~name,
    x = ~count,
    # marker = list(color = colors[1]),
    type = "bar",
    orientation = "h"
  ) %>%
  layout(
    paper_bgcolor = "#F5F5F5",
    plot_bgcolor = "#F5F5F5",
    xaxis = list(
      title = "company",
      categoryorder = "total descending"
    ),
    yaxis = list(
      title = "count"
    )
  )

DATA

data <- structure(list(name = c(
  "Company1", "Company2", "Company3", "Company4",
  "Company5", "Company6", "Company7", "Company8", "Company9", "Company10"
), count = c(
  7067L, 810L, 9524L, 2878L, 4014L, 6565L, 772L, 4810L,
  785L, 1330L
)), class = "data.frame", row.names = c(
  "1", "2",
  "3", "4", "5", "6", "7", "8", "9", "10"
))
  • Related