首页 > 解决方案 > 用缺失值绘制正确的颜色和有序因子

问题描述

我正在使用几个具有一些分类值的数据框并从中创建图表。

例如,数据可能看起来像这样。请注意,“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)
  )

使颜色与我的名字对齐的最佳方法是什么?谢谢!

标签: rggplot2merge

解决方案


两个选项,简单且可能更具视觉吸引力的版本使用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 创建

在此处输入图像描述


推荐阅读