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?
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"))

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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With