分配颜色以遵循特定顺序

K. *_*aya 1 r ggplot2

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

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()
Run Code Online (Sandbox Code Playgroud)

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

col <- as.character(mycolor$color)
names(col) <- as.character(mycolor$grp)
Run Code Online (Sandbox Code Playgroud)

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

Duc*_*uck 5

尝试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)
Run Code Online (Sandbox Code Playgroud)

使用双方可重现的数据:

#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)
Run Code Online (Sandbox Code Playgroud)

输出:

在此处输入图片说明

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