R:使用plot_ly()更改条形图中的条形宽度

时间:2020-06-25 08:50:21

标签: r plotly bar-chart

我有一个数据框

jest.spyOn(mockApi, 'getNotifications').mockResolvedValue({hasStores: false })

我正在尝试使用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 )) 绘制条形图。

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')) 参数时,宽度不会改变。

如何在R中使用plot_ly()设置条的宽度?

2 个答案:

答案 0 :(得分:0)

您可以通过layout自变量bargap获得细条。试试这个:

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)

第二种方法是通过add_bars(width = 0.2)添加条形(很奇怪,这是可行的...):

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

答案 1 :(得分:0)

您可以在width中使用add_bars参数。您必须设置每个单独的条的宽度:

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