R 为条形图设置自定义颜色

编程入门 行业动态 更新时间:2024-10-10 21:30:29
本文介绍了R 为条形图设置自定义颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的 Shiny 应用中有一个 plotly 条形图,我想为结果条形图中的每一列设置特定颜色.

I've got a plotly bar chart in my Shiny app, and I'd like to set specific colors each column in the resulting bar chart.

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

然而,结果图没有显示我指定的任何颜色.

However the resulting plot does not show any of the colors I specify.

我做错了什么?任何指针将不胜感激.

What am I doing incorrectly? Any pointers would be very appreciated.

推荐答案

您可以将颜色分配给一个向量:

You could assign your colors to a vector:

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

然后在稍微修改的循环中添加跟踪.

and then add the traces in a slightly modified loop.

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

更多推荐

R 为条形图设置自定义颜色

本文发布于:2023-07-19 13:48:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1157120.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   颜色   条形图

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!