R语言 条形图中的虚线

t8e9dugd  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(255)

我想在Plotly barplot R中有一条虚线。
在下面的代码中,我在line属性中有dash = 'dash',但它不起作用。

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

fig
flseospp

flseospp1#

到目前为止,条形图中的line不包含参数“dash”。但是,您可以使用shapes添加虚线。
在代码中,我添加了注解来解释什么是做什么的。如果有什么不清楚的地方,请告诉我。
首先,我计算每个条形图的开始和结束在x轴上的paper空间中的位置。默认情况下,图的paper空间,无论x轴还是y轴都等于1。您必须将1除以条形图的数量以获得每个条形图的“空间”的开始。默认情况下,在每一条之前和之后都增加了10%的空间。(你可以手动改变空间。)
在计算了x轴上每个条形图的开始和结束位置之后,我使用类型rect构建shapes
在创建条形图时,我在marker中省略了对line的原始调用。
看看吧:

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())

相关问题