r - 分配颜色以遵循特定顺序
问题描述
我想制作以下示例数据的时间序列图。
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)
. 我应该在这里改变什么?
解决方案
尝试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()
:
推荐阅读
- asp.net-core - 我应该将 Razor Pages 和 Blazor 混合使用,还是将它们分开?
- python - 如何返回任意两个字母之间的最大距离(az 忽略大小写)?
- linux - 同时使用iperf和ping mininet
- sql-server - 执行动态 SQL 并插入到存储过程中创建的表中?
- elasticsearch - 获取弹性搜索的相关数据
- reactjs - React 表单优化
- javascript - HTML, Javascript 游戏,我想找到一种在页面显示上播放声音的方法
- spring-boot - 将 Jersey 与 Spring Boot 一起使用
- xamarin.forms - 无法在 AppBar 上更改颜色
- python - 在 Python > 3 上使用带有部分和映射失败的多处理脚本,在 2.7 上工作正常,无法腌制“_thread.lock”