首页 > 解决方案 > 分配颜色以遵循特定顺序

问题描述

我想制作以下示例数据的时间序列图。

library(tidyverse)

df <- read.table(text = "
dates       cat dog mat sat tap 
1997-01-01  0.2 0.2 0.4 0.1 0.1
1997-01-02  0.3 0.2 0 0.5 0
1997-01-03  0.1 0 0.2 0.3 0.4
", header = TRUE,fill=TRUE)

df %>% 
  mutate(dates = as.Date(dates)) %>% 
  gather(variable, value, cat:tap) %>% 
  ggplot(aes(x = dates, y = value, fill = variable)) +
  geom_area()

我创建了一个单独的文件并分配了一组颜色,并希望它遵循文件中的顺序。

col <- as.character(mycolor$color)
names(col) <- as.character(mycolor$grp)

但是,我总是在使用scale_fill_manual(values = col). 我应该在这里改变什么?

标签: rggplot2

解决方案


尝试variable使用颜色设置为因素。由于您不共享mycolor,它必须包含与您重塑的值相同的名称。这里的代码:

library(tidyverse)
#Colors
col <- as.character(mycolor$color)
names(col) <- as.character(mycolor$grp)
#Data and plot
df %>% 
  mutate(dates = as.Date(dates)) %>% 
  gather(variable, value, cat:tap) %>% 
  mutate(variable=factor(variable,levels = as.character(mycolor$grp),ordered = T)) %>%
  ggplot(aes(x = dates, y = value, fill = variable)) +
  geom_area()+
  scale_fill_manual(values = col)

使用双方可重现的数据:

#Mycolor
mycolor <- data.frame(color=c('yellow','purple','blue','pink','magenta'),
                      grp=c('tap','dog','cat','sat','mat'),stringsAsFactors = F)
#Colors
col <- as.character(mycolor$color)
names(col) <- as.character(mycolor$grp)
#Data and plot
df %>% 
  mutate(dates = as.Date(dates)) %>% 
  gather(variable, value, cat:tap) %>% 
  mutate(variable=factor(variable,levels = as.character(mycolor$grp),ordered = T)) %>%
  ggplot(aes(x = dates, y = value, fill = variable)) +
  geom_area()+
  scale_fill_manual(values = col)

输出:

在此处输入图像描述

现在您可以看到使用后的顺序如何mycolor反映在最终图中mutate()


推荐阅读