简体   繁体   English

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

[英]plotly, unable to change individual bar colors in R

I'm really new to using plotly and after reading the documentation, I can't seem to figure out why this code won't change the colours of the individual bars.我对使用 plotly 真的很陌生,在阅读了文档后,我似乎无法弄清楚为什么这段代码不会改变单个条形的颜色。

My data set is mtcars reduced to only the MPG and CYL columns.我的数据集是 mtcars 减少到只有 MPG 和 CYL 列。

This is the code that I'm using:这是我正在使用的代码:

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

For some reason it only displays all 3 bars (4/6/8 cyl) as black.出于某种原因,它只将所有 3 个条形 (4/6/8 cyl) 显示为黑色。 What am I doing wrong?我究竟做错了什么?

Thanks.谢谢。

Thanks @mischva11!谢谢@mischva11!

Yes, I realize now my data was not appropriate.是的,我现在意识到我的数据不合适。 The following fixed it and achieved what I was initially trying to do anyway:以下修复了它并实现了我最初尝试做的事情:

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

And worked as it should.并按其应有的方式工作。 Thanks.谢谢。

Another solution using only dplyr:仅使用 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")
  )

The output:输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM