r - 根据另一个变量的值控制颜色的顺序
问题描述
我想根据另一个变量的值来控制点/线的颜色顺序。
一个例子来解释我想要做什么:
library(tidyverse)
set.seed(12345)
# example data
df <- data.frame(
country = rep(c("India", "Sweden", "Germany", "Finland", "NZ", "Aus"), each = 4),
year = rep(2010:2013, 6),
value = sample(1:100, 24)
)
# create a rank column
df <- df %>%
group_by(year) %>%
mutate(rank = rank(value, ties.method = "random"))
# plot
ggplot(df, aes(year, rank, color = country)) +
geom_point(size = 5) +
geom_line(size = 2) +
scale_colour_viridis_d(direction = 1) +
scale_y_reverse()
viridis 调色板是有序的,默认情况下,排序是根据颜色变量(countires)的字母顺序设置的,例如,Aus 最暗(紫色)到瑞典最亮(黄色)。
有没有办法根据 2010 年的变量更改要订购的颜色,rank
例如印度 = 最暗(紫色)到芬兰最轻(黄色)?
在我的真实数据集中有超过 6 个国家,所以我不想手动为国家级别分配颜色。
解决方案
这应该适合你。基本上,你想让你的国家名称成为一个有序的因素。
library(tidyverse)
set.seed(12345)
# example data
df <- data.frame(
country = rep(c("India", "Sweden", "Germany", "Finland", "NZ", "Aus"), each = 4),
year = rep(2010:2013, 6),
value = sample(1:100, 24)
)
# create a rank column
df <- df %>%
group_by(year) %>%
mutate(rank = rank(value, ties.method = "random")) %>%
arrange(year, rank) %>%
# Arranging first is important because as_factor creates a factor ordered
# by the order in which the values appear in the dataframe
mutate(country = as_factor(country))
# plot
ggplot(df, aes(year, rank, color = country)) +
geom_point(size = 5) +
geom_line(size = 2) +
scale_colour_viridis_d(direction = 1) +
scale_y_reverse()
推荐阅读
- ms-access - MS Access 获取数据表中的子行数
- javascript - React - 重叠 css 文件
- reactjs - 事件在 axios 拦截器内触发两次
- python - Discord 机器人加入/离开
- interface - 无法弄清楚 MPS 错误:“角色 XY 中的孩子不属于概念 X”
- rundeck - Rundeck 作业返回 curl: (52) 来自服务器的空回复
- c - 我可以刷新多行输出吗?
- python - 一句话写出嵌套的for循环
- javascript - javascript raycaster 引擎中的鱼眼协作
- sendgrid - 如何从 sendgrid api 获取动态模板数据