Tester_Y
Tester_Y

Reputation: 377

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.

My data set is mtcars reduced to only the MPG and CYL columns.

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. What am I doing wrong?

Thanks.

Upvotes: 0

Views: 1827

Answers (2)

vpz
vpz

Reputation: 1044

Another solution using only 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:

enter image description here

Upvotes: 1

Tester_Y
Tester_Y

Reputation: 377

Thanks @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.

Upvotes: 1

Related Questions