Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Change the width of the bars in the bar chart using plot_ly()

I am having a dataframe

df <- structure(list(quarter = c(
  "Q1 2019",
  "Q2 2019", "Q3 2019", "Q4 2019", "Q1 2020", "Q2 2020"
), average = c(
  309L,
  279L, 284L, 246L, 232L, 235L
)), class = "data.frame", row.names = c(
  NA,
  -6L
))

And I am trying to plot a bar chart using plot_ly().

 plot_ly(df, x = df$quarter, y=df$average,type = 'bar',
        marker = list(color = "#d3b348"), 
        text = df$average, textposition = 'outside',hoverinfo = 'text')%>%
  layout(showlegend = FALSE,hoverlabel = list(bgcolor= 'white'))

I am unable to change the width of each bar. I need a thin bar and when I pass width argument, the width doesn't gets changed.

How can I set the width of the bars using plot_ly() in R?

like image 965
Nevedha Ayyanar Avatar asked Oct 24 '25 02:10

Nevedha Ayyanar


2 Answers

You can get thin bars via the layout argument bargap. Try this:

plot_ly(df,
  x = df$quarter, y = df$average, type = "bar",
  marker = list(color = "#d3b348"),
  text = df$average, textposition = "outside", hoverinfo = "text"
) %>%
  layout(showlegend = FALSE, hoverlabel = list(bgcolor = "white"), bargap = 0.8)

And a second approach would be to add the bars via add_bars(width = 0.2) (Weird that this works ...):

plot_ly(df,
        x = df$quarter, y = df$average,
        marker = list(color = "#d3b348"),
        text = df$average, textposition = "outside", hoverinfo = "text"
) %>%
  add_bars(width = .2) %>% 
  layout(showlegend = FALSE, hoverlabel = list(bgcolor = "white"))

enter image description here

like image 164
stefan Avatar answered Oct 25 '25 15:10

stefan


You can use the width argument in add_bars. You have to set the width of each individual bar:

plot_ly(df) %>% add_bars(x = ~quarter, y=~average, type = 'bar', 
        width = c(.1,.1,.1,.2,.2,.2),
        marker = list(color = "#d3b348"), 
        text = ~average, textposition = 'outside', hoverinfo = 'text')%>%
  layout(showlegend = FALSE, hoverlabel = list(bgcolor= 'white'))
like image 39
Stéphane Laurent Avatar answered Oct 25 '25 17:10

Stéphane Laurent