我正在尝试在R中生成哑铃图。在这种情况下,有四行,它们需要各自具有不同的特定颜色。我使用colorRampPalette()将颜色定义为数据集的一部分。然后,当我制作情节时,颜色会以不恰当的方式混合。请参见下图,特别是图例。
正如你所看到的,根据传说,橙色应该是#7570B3。但这不正确。颜色7570B3是紫色的!出于这个原因,我在数据集中定义的颜色在图中混合。 " Alt 2"声音是橙色和" Alt 3"应该是紫色的。
有谁知道如何解决这个问题?任何帮助都将非常感激。
以下是代码的简单版本:
table_stats_scores <- data.frame(alt=c("alt1","alt2","alt3","alt4"),
average=c(15,20,10,5),
dumb_colors= colorRampPalette(brewer.pal(4,"Dark2"))(4),
min=c(10,15,5,0),max=c(20,25,15,10)
)
table_stats_scores # This is the dataset
table_stats_scores <- table_stats_scores[order(-
table_stats_scores$average),] # ordering
table_stats_scores$alt <- factor(table_stats_scores$alt,
levels = table_stats_scores$alt[order(table_stats_scores$average)])
# giving factor status to alternatives so that plot_ly() picks up on this
p <- plot_ly(table_stats_scores, x=table_stats_scores$average, color = ~
dumb_colors,
y=table_stats_scores$alt,text=table_stats_scores$alt) %>%
add_segments(x = ~min, xend = ~max, y = ~alt, yend = ~alt,name = "Min-Max
range", showlegend = FALSE, line = list(width = 4)) %>%
add_markers(x = ~average, y = ~alt, name = "Mean",
marker=list(size=8.5),showlegend = FALSE) %>%
add_text(textposition = "top right") %>%
layout(title = "Scores of alternatives",
xaxis = list(title = "scores"),
yaxis = list(title = "Alternatives")
)
p
答案 0 :(得分:1)
是的颜色可能是一个问题,因为有几种方法可以指定它,并且数据框中各种元素的分配顺序很难保持同步。
进行了以下更改:
brewer.pal
颜色。最好用明显的东西进行调试。color
参数更改为alt
列,因为它实际上只是间接用于设置颜色,而且主要用于确定图例中的文本。text
参数(而不是alt
),以便我可以看到它是否正确分配颜色。table_stat_scores
排序,因为否则它按错误的顺序分配颜色(不完全理解这一点 - 似乎内部有一些神秘的排序/重新排序)add_segments
和add_markers
添加了颜色参数,以便他们使用相同的列以相同的方式设置颜色。我认为这会让你想要你想要的东西:
library(plotly)
library(RColorBrewer)
table_stats_scores <- data.frame(alt=c("alt1","alt2","alt3","alt4"),
average=c(15,20,10,5),
dumb_colors= colorRampPalette(brewer.pal(4,"Dark2"))(4),
min=c(10,15,5,0),max=c(20,25,15,10)
)
table_stats_scores # This is the dataset
table_stats_scores$bright_colors <- c("#FF0000","#00FF00","#0000FF","#FF00FF")
table_stats_scores <- table_stats_scores[order(table_stats_scores$average),] # ordering
table_stats_scores$alt <- factor(table_stats_scores$alt,
levels = table_stats_scores$alt[order(table_stats_scores$average)])
# giving factor status to alternatives so that plot_ly() picks up on this
p <- plot_ly(table_stats_scores, x=~average, color = ~alt, y=~alt,text=~bright_colors) %>%
add_segments(x = ~min, xend = ~max, y = ~alt, yend = ~alt,name = "Min-Max range",
colors=~bright_colors, showlegend = FALSE, line = list(width = 4)) %>%
add_markers(x = ~average, y = ~alt, name = "Mean",
marker=list(size=8.5,colors=~bright_colors),showlegend = FALSE) %>%
add_text(textposition = "top right") %>%
layout(title = "Scores of alternatives",
xaxis = list(title = "scores"),
yaxis = list(title = "Alternatives")
)
p
产生这个: