r - 用plotly绘制镜像条形图

标签 r plotly

我想知道如何垂直镜像两种条形(正数和负数),如下图:

enter image description here

到目前为止,我只能让它们成为镜像,但并排站立,如下所示:

enter image description here

数据:

library(plotly)
time <- c("2018-10","2018-11","2018-12")
add <- c(20,15,20)
delete <- c(-5,-10,-2)
total <- c(60,65,83)
df <- data.frame(time,add,delete,total)

plot_ly(df) %>%
    add_trace(x = ~time, y = ~add, type = 'bar', name = 'add',
              marker = list(color = '#33adff'),
              hovertemplate = paste('add: %{y}',
                                    '<br>time: %{x}<br>')) %>%
    add_trace(x = ~time, y = ~delete, type = 'bar', name = 'delete',
              marker = list(color = '#ff6666'),
              hovertemplate = paste('delete: %{y}',
                                    '<br>time: %{x}<br>'))

最佳答案

可以使用barmode="overlay"解决该问题。
您需要将df数据集设置为长数据格式。

library(plotly)
time <- c("2018-10","2018-11","2018-12")
add <- c(20,15,20)
delete <- c(-5,-10,-2)
total <- c(60,65,83)
n <- length(time)
df <- data.frame(time=rep(time,2), y=c(add, delete), grp=rep(c("Add","Delete"),each=n))

plot_ly(df) %>%
    add_trace(x = ~time, y = ~y, color=~grp, text=~grp, type = 'bar', 
              marker = list(color = c(rep('#33adff',n), rep('#ff6666',n))),
              hovertemplate = paste('%{text}: %{y}', '<br>time: %{x}<br>')) %>%
    layout(barmode="overlay")

enter image description here

关于r - 用plotly绘制镜像条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58074562/

相关文章:

r - 在R中从png切换到pdf时如何保持比例

python - 如何避免 plotly 中的重复图例标签或传递自定义图例标签

python - 在 Plotly 散点图中按颜色添加图例

javascript - 时间模式下的 Plot.ly : fixed grid size

r - 仅在单击 Shiny 中的操作按钮后才更新服务器上的内容

r - Plotly 中子图的标题

r - 在 lme4 中查看标准误差和参数估计

r - 如何仅打开一个文件的工作目录中的下一个文件夹?

r - switch() 语句用法

windows - 以编程方式清除 R 控制台