簡體   English   中英

繪圖,無法更改 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 cyl) 顯示為黑色。 我究竟做錯了什么?

謝謝。

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

輸出:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM