簡體   English   中英

R 為條形圖設置自定義顏色

[英]R Plotly set custom colors for bar chart

我的 Shiny 應用程序中有一個可plotly條形圖,我想為結果條形圖中的每一列設置特定的顏色。

#Here's some reproducible data
df=data.frame(Month=c("Jan","Feb","Mar","Apr","May","Jun"),Criteria1=c(10,15,20,15,7,6),Criteria2=c(3,8,5,7,9,10),Criteria3=c(11,18,14,9,3,1))

#Plot

colNames <- names(df)[-1] #Month is the first column

# Here is where I set the colors for each `Criteria`, assuming that the order of colors follows the same order as the factor levels of the `Criteria`.

p <- plotly::plot_ly(marker=list(colors=c('#CC1480', '#FF9673', '#E1C8B4')))

for(trace in colNames){
  p <- p %>% plotly::add_trace(data = df, x = ~Month, y = as.formula(paste0("~`", trace, "`")), name = trace, type = "bar")
}

p %>% 
  layout(title = "Trend Over Time",showlegend = FALSE,
         xaxis = list(title = ""),
         yaxis = list (title = "Monthly Count of QoL Tweets"))

但是,生成的圖沒有顯示我指定的任何顏色。

我做錯了什么? 任何指針將不勝感激。

我認為這里不需要循環,以下內容還提供了在df熔化時為特定級別選擇顏色的更多控制,個別級別Criteria1Criteria2Criteria3

library(plotly)
library(reshape2)

#Yout data.frame
df <- data.frame(Month = c("Jan","Feb","Mar","Apr","May","Jun"),
                 Criteria1 = c(10,15,20,15,7,6),
                 Criteria2 = c(3,8,5,7,9,10),
                 Criteria3 = c(11,18,14,9,3,1))

melt(df, id.vars = 'Month') %>% plot_ly(x = ~Month, y = ~value, type = 'bar', 
  color = ~variable,
  colors = c(Criteria1 = '#CC1480', Criteria2 = '#FF9673', Criteria3 = '#E1C8B4'))

在此處輸入圖片說明

您可以將顏色分配給向量:

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

然后在稍微修改的循環中添加跟蹤。

p <- plotly::add_trace(p, 
                       x = df$Month, 
                       y = df[,trace], 
                       marker = list(color = colors[[match(trace, colNames)]]), 
                       name = trace, 
                       type = "bar")
}

這將為您提供以下圖表

在此處輸入圖片說明

完整代碼

library("plotly")
df=data.frame(Month=c("Jan", "Feb","Mar", "Apr", "May", "Jun"),
              Criteria1 = c(10, 15,20,15,7,6),
              Criteria2 = c(3, 8, 5, 7, 9, 10),
              Criteria3 = c(11, 18, 14, 9, 3, 1))

colNames <- names(df)[-1] #Month is the first column
colors <- c('#CC1480', '#FF9673', '#E1C8B4')
p <- plotly::plot_ly()

#colNames = c('Criteria1')
for(trace in colNames){
  p <- plotly::add_trace(p, 
                         x = df$Month, 
                         y = df[,trace], 
                         marker = list(color = colors[[match(trace, colNames)]]), 
                         name = trace, 
                         type = "bar")
}

p

暫無
暫無

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

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