r - 用缺失值绘制正确的颜色和有序因子
问题描述
我正在使用几个具有一些分类值的数据框并从中创建图表。
例如,数据可能看起来像这样。请注意,“Marcus”不在friends_2
friends <- data.frame(
name = factor(c("Nicole", "Sara", "Marcus", "Derek", "Conor", "Anna")),
number = c(.4, .8, 1, .1, .2, .2)
)
friends_2 <- data.frame(
name = factor(c("Nicole", "Sara", "Derek", "Conor", "Anna")),
score = c(50, 10, 20, 90, 15)
)
这是一些绘图代码。我有一个旨在匹配的调色板,names
但因为“Marcus”不在friends_2
,颜色不再匹配。
cbp1 <- c("#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E", "#E6AB02")
ggplot(friends, aes(x=name, y=number)) +
scale_fill_manual(values = cbp1) +
geom_bar(
stat = "identity",
width = 0.5,
aes(fill = name)
)
ggplot(friends_2, aes(x=name, y=score)) +
scale_fill_manual(values = cbp1) +
geom_bar(
stat = "identity",
width = 0.5,
aes(fill = name)
)
使颜色与我的名字对齐的最佳方法是什么?谢谢!
解决方案
两个选项,简单且可能更具视觉吸引力的版本使用facet_wrap
library(ggplot2)
library(tidyr)
library(dplyr)
f_levs <- c("Nicole", "Sara", "Marcus", "Derek", "Conor", "Anna")
friends <- data.frame(
name = factor(c("Nicole", "Sara", "Marcus", "Derek", "Conor", "Anna"), levels = f_levs, ordered = TRUE),
number = c(.4, .8, 1, .1, .2, .2)
)
friends_2 <- data.frame(
name = factor(c("Nicole", "Sara", "Derek", "Conor", "Anna"), levels = f_levs, ordered = TRUE),
score = c(50, 10, 20, 90, 15)
)
cbp1 <- c("#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E", "#E6AB02")
p1 <- ggplot(friends, aes(x=name, y=number)) +
scale_fill_manual(values = cbp1, breaks = f_levs) +
geom_bar(
stat = "identity",
width = 0.5,
aes(fill = name)
) +
ggtitle("p1 - friends")
p2 <- ggplot(friends_2, aes(x=name, y=score)) +
scale_fill_manual(values = cbp1, breaks = f_levs) +
geom_bar(
stat = "identity",
width = 0.5,
aes(fill = name)
) +
ggtitle("p2 - friends_2")
带有 facet_wrap
将数据组合成“长”格式进行绘图。
f <-
friends %>%
bind_rows(friends_2) %>%
mutate(df = case_when(is.na(score) ~ "friends",
TRUE ~ "friends_2")) %>%
pivot_longer(-c(name, df), names_to = "var", values_to = "val", values_drop_na = TRUE)
p3 <-
ggplot(f, aes(name, val, fill = name))+
geom_col()+
facet_wrap(~var, scales = "free_y", ncol = 1) +
ggtitle("p3 - facet_wrap all friends")
由reprex 包(v0.3.0)于 2020-05-13 创建
推荐阅读
- eclipse - Scala Script 在 REPL 中工作,但在 Scala IDE 上失败
- asp.net - DbContext.Query 不接受泛型类型 T,如何在 dot net core api 中进行泛型 DbContext 查询?
- apache-spark - 在 YARN 上使用 Spark 时 maxExecutors、num-executors 和 initialExecutors 之间的关系是什么?
- angular - 如何在角度中引入类似自定义生命周期事件的钩子
- jhipster - KeyCloak Docker compose:禁用表的覆盖
- angular - 如何在 Pusher 中向频道的所有成员广播消息事件?
- python - 如何获取json中键的所有值,而不仅仅是最后一组?
- github - 如何将 gerrit 存储库与 github 存储库同步?
- linux - 启动 mongodb 服务器时出错
- c++ - 同一文件的不同哈希值(使用 ifstream 完成读取)