assign color to follow particular order

Viewed 128

I want to make a timeseries plot of the following sample data.

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()

I have created a separate file and assigned a set of colors and want it to follow the order in the file.

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

However, I always get it ordered alphabetically when using scale_fill_manual(values = col). What should I change here?

1 Answers

Try setting variable as factor using the colors. As you do not shared mycolor, it must contain the same names as you reshaped values. Here the code:

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)

Using reproducible data on both sides:

#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)

Output:

enter image description here

Now you can see how the order of mycolor is reflected in the final plot after using mutate():

Related