I want to have a dashed line around bar in plotly barplot.
In the following code, I had dash = 'dash' in line attribute but it's not working.
library(plotly)
x <- c('Product A', 'Product B', 'Product C')
y <- c(20, 14, 23)
text <- c('27% market share', '24% market share', '19% market share')
data <- data.frame(x, y, text)
fig <- plot_ly(data, x = ~x, y = ~y, type = 'bar', text = text,
marker = list(color = 'rgb(158,202,225)',
line = list(color = 'rgb(8,48,107)',
width = 1.5, dash = "dash")))
fig <- fig %>% layout(title = "January 2013 Sales Report",
xaxis = list(title = ""),
yaxis = list(title = ""))
As of right now, line in bar plot doesn't include the argument "dash". However, you can add a dashed line using shapes.
In the code, I've added comments to explain what does what. If there is anything that's unclear, let me know.
First, I calculate where the start and end of each of the bars are in paper space on the x-axis. By default the paper space of the plot, whether x or y axes is equal to 1. You have to divide one by the number of bars to get the start of each bar's 'space.' By default, there is a 10% space added before and after each bar. (You can manually change the space.)
After calculating the start and end of each bar on the x-axis, I build the shapes using the type rect.
When I create the bar plot, I leave out your original call for line within marker.
Check it out:
doThis <- function() {
# 3 bars, 10% of bar space on each side standard, paper space = 1
positions <- lapply(0:2, function(k) {
p1 = k * 1/3 + .1 * 1/3 # left side of bar paper space (x-axis)
p2 = k * 1/3 + .9 * 1/3 # right side of bar paper space (x-axis)
c(p1, p2)
})
lapply(1:3, function(j) {
list(type = "rect",
x0 = positions[[j]][[1]], # as calculated in paper space
x1 = positions[[j]][[2]],
y0 = 0, y1 = data$y[j], # this assumes the data is ordered as plotted
xref = "paper", yref = "y",
line = list(color = 'rgb(8,48,107)', # from your original code
width = 1.5, dash = "dash"))
})
}
# your original code, less the call for line
plot_ly(data, x = ~x, y = ~y, type = "bar", text = text,
marker = list(color = 'rgb(158, 202, 225)')) %>%
layout(title = "January 2013 Sales Report",
xaxis = list(title = ""), yaxis = list(title = ""),
shapes = doThis())

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