簡體   English   中英

以R設置的方式繪制單獨堆積的條形寬度

[英]Plotly in R Set Individual Stacked Bar Width

在Plotly教程中,我知道如何設置單個條形寬度,如下所示:

library(plotly)

x= c(1, 2, 3, 5.5, 10)
y= c(10, 8, 6, 4, 2)
width = c(0.8, 0.8, 0.8, 3.5, 4)
data <- data.frame(x, y, width)

p <- plot_ly(data) %>%
  add_bars(
    x= ~x,
    y= ~y,
    width = ~width
  )

它將產生各種寬度:

在此處輸入圖片說明

但是,當我嘗試使用堆積的條形圖復制它時,它不起作用:

x = c(1, 2, 3, 5.5, 10,1, 2, 3, 5.5, 10)
y = c(10, 8, 6, 4, 2,0,2,4,6,8)
width = c(0.8, 0.8, 0.8, 3.5, 4,0.8, 0.8, 0.8, 3.5, 4)
group = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B")
data <- data.frame(x, y, width, group)

p <- data %>%
  group_by(group) %>%
  plot_ly(
    x= ~x,
    y= ~y,
    width = ~width,
    color = ~group,
    colors = 'Reds',
    type = "bar"
  ) %>%
  layout(barmode = 'stack')

它給出了錯誤:

> print(p)
Error in validateCssUnit(sizeInfo$width) : 
  CSS units must be a single-element numeric or character vector
In addition: Warning message:
In is.na(x) : is.na() applied to non-(list or vector) of type 'language'

當然注釋掉“ width =〜width”,然后我的代碼就可以完美地工作了。 但是我確實需要調整圖表的條形寬度。 有誰知道解決方案嗎?

您可以使用ggplotly作為替代。 您可以嘗試以下方法:

ggplotly(ggplot(data = data, aes(x = x, y = y, fill = group, width = width)) + geom_col() + theme_bw())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM