plotly,无法更改 R 中的单个条形颜色

plotly, unable to change individual bar colors in R

我对使用 plotly 很陌生,在阅读了文档之后,我似乎无法弄清楚为什么这段代码不会改变各个条形图的颜色。

我的数据集是 mtcars 减少到只有 MPG 和 CYL 列。

这是我正在使用的代码:

mtcars %>%
  plot_ly(x = ~cyl,
          y = ~mpg, 
          type = "bar",
          marker = list(color = c('rgba(204,204,204,1)', 'rgba(222,45,38,0.8)',
                                  'rgba(204,204,204,1)') )
          ) %>%
  layout(title = "Test Chart",
         xaxis = list(title = "Cylinders"),
         yaxis = list(title = "MPG")
         )

出于某种原因,它只将所有 3 条(4/6/8 柱)显示为黑色。我做错了什么?

谢谢。

谢谢@mischva11!

是的,我现在意识到我的数据不合适。以下修复了它并实现了我最初尝试做的事情:

df_v <- sqldf("
          SELECT cyl, AVG(mpg) AS 'Average MPG'
          FROM mtcars_reduced
          GROUP BY cyl
          ORDER BY cyl DESC


          ")


df=df_v

colors2 <- c('#CC1480', '#FF9673', '#E1C8B4')


                     p <- plot_ly(
                     x = df$cyl,
                     y = df$'Average MPG', 
                     type = "bar",
                     marker = list(color = colors2)
                                 )%>%
                     ##color = I("black"))

                     layout(title = "Test Chart",
                            xaxis = list(title = "Cylinders"),
                            yaxis = list(title = "MPG")
                            )


p

并按预期工作。谢谢

另一个只使用 dplyr 的解决方案:

library(dplyr)
library(plotly)

mtcars %>%
  group_by(cyl) %>%
  summarise(Average_MPG = mean(mpg)) %>%
  plot_ly(x = ~cyl,
          y = ~Average_MPG, 
          type = "bar",
          marker = list(color = c('#CC1480', '#FF9673', '#E1C8B4') )
          )%>%
  layout(title = "Test Chart",
         xaxis = list(title = "Cylinders"),
         yaxis = list(title = "MPG")
  )

输出: