R语言 从变量中选择条形的颜色

vnjpjtjt  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(120)

我想设置一些以前选择的颜色到我的条形图。例如,我想法拉利是红色,奔驰绿松石...
例如,您可以使用以下简单数据集:

structure(list(points = c(3183, 27, 210, 334, 352, 898, 559, 812, 3796, 2508), name = c("Ferrari", 
"Williams", "Aston Martin", "Haas F1 Team", "AlphaTauri", "McLaren", 
"Alfa Romeo", "Alpine F1 Team", "Red Bull", "Mercedes"), color = c("red", "lightblue", "darkgreen", "darkred", "black", "grey", "darkblue", "pink", "yellow", "turquoise")), row.names = 1:9, class = "data.frame")

我尝试使用以下代码:

library(plotly)
library(dplyr)
plot_ly(data, x =~name, y=~points, color = ~name, colors = ~color)%>%add_bars()

我得到了下面的结果(颜色不是我想要的):
Result

c0vxltue

c0vxltue1#

您的name变量被强制为因子并按字母顺序排序。请将其设为因子并与您定义的颜色顺序相对应。
df$name <- factor(df$name, levels = unique(df$name))

相关问题