0
votes

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.

2
Can you make your code reproducible?BIM
Just remove the _reduced behind the mtcars code works also with full dataframemischva11
the problem is you are plotting 32 bar plots, because the data is completly used wrong for bar charts. Every single cyl value has a single mpg value, which is one single bar (you have 32 pairs). So you get 32 bars on 4/6/8 which are overlappingmischva11

2 Answers

1
votes

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.

1
votes

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