将(有序)因子映射到ggplot中的颜色 [英] mapping (ordered) factors to colors in ggplot
问题描述
考虑此示例
data_frame(mylabel = c('month 18',
'month 19',
'month 20',
'month 21',
'month 22'),
value = c(5,10,-2,2,0),
time = c(1,2,3,4,5)) %>%
ggplot(aes( x= time, y = value, color = mylabel)) +
geom_point(size = 7)
在这里您可以看到变量 mylabel
具有自然的顺序:18个月在19个月之前,等等.
Here you can see that the variable mylabel
has a natural ordering: month 18 comes before month 19 etc.
但是, ggplot
选择的颜色不会保留这种自然顺序.在我的真实数据集中,我有大约50个不同的月份,并且我想使用一种色标来使这种增加更加直观(例如从冷到热).
However, this natural ordering is not preserved by the colors chosen by ggplot
. In my real dataset, I have about 50 different months and I would like to use a color scale that makes this increase more intuitive (say from cold to hot).
我该怎么做?谢谢!
推荐答案
您可以使用viridis色标或另一种颜色更好的色标来指示顺序.
you can use the viridis color scale or another one which is better colored to indicate the order.
为相似的色标提供了多个选项(选项="A"至"D").通过 direction = -1
There are several options included for similar color scales (option = "A" through "D"). Change the order by direction = -1
我添加了一个步骤,以使订购更好,以防万一月份未正确列出.它可以工作,但是我敢肯定有一种更简单的方法.从名称中拉出month#(必须将其从 char
转换为 numeric
),然后将其分解为适当的顺序.
I've added a step to get better ordering, in case months are listed incorrectly. It works, but I'm sure there's a simpler way. Pull out the month# from the name (has to be converted from char
to numeric
) and then factor it which will use the proper order.
library(tidyverse)
data_frame(mylabel = paste("month", 1:10),
value = rnorm(length(mylabel)),
time = seq_along(mylabel)) %>%
mutate(month_number = factor(as.numeric(gsub("month ([0-9]+)", "\\1", mylabel)))) %>%
ggplot(aes( x= time, y = value, color = month_number)) +
geom_point(size = 7) +
scale_color_viridis_d(option = "B", direction = -1)
由 reprex软件包(v0.2.1)创建于2018-11-30
这篇关于将(有序)因子映射到ggplot中的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!