r - 将数据集中不存在的值添加到图例

标签 r ggplot2

我试图在 geom_bar 图表的图例中包含 A、B、C、D 和 E,即使这些值在我的数据集中不存在。在 R 中有没有办法做到这一点?下面是我目前拥有的代码...

classes_filtered <- classes %>% filter(teacher == "Mrs. Smith") %>% summarize(total_students = sum(grades))

possible_grades <- c("A", "B", "C", "D", "E", "NA")

#grades$type <- factor(grades$type, levels = c("A", "B", "C", "D", "E", "NA"))

ggplot(classes_filtered, aes(x = subject, y = total_students, fill = Grades_Given)) + 
  geom_bar(stat = "identity", colour = "black") + 
#  scale_color_manual(values = c("A", "B", "C", "D", "E", "NA"), drop = FALSE) +
  labs(x="Subject", y="Number of Students", fill = "Grade") +
  ggtitle("Grades Given per Subject")

以及我正在使用的数据集。非常感谢任何帮助。谢谢。

classes_filtered  <- read.csv(text="
teacher, subject, Grades_Given, total_students
Mrs. Smith, English, NA, 1
Mrs. Smith, Algebra, C, 2
Mrs. Smith, Algebra, D, 1
Mrs. Smith, Geometry, C, 8
Mrs. Smith, Geometry, D, 7
Mrs. Smith, Biology, C, 6
Mrs. Smith, Biology, D, 7
Mrs. Smith, Biology, NA, 3
Mrs. Smith, Chemistry, C, 1
Mrs. Smith, Chemistry, D, 4
Mrs. Smith, Chemistry, NA, 2
Mrs. Smith, Literature, C, 7
Mrs. Smith, Literature, D, 4
Mrs. Smith, Literature, NA, 2
Mrs. Smith, Spanish, B, 2
Mrs. Smith, Spanish, C, 1
Mrs. Smith, French, D, 1
Mrs. Smith, Latin, C, 4
Mrs. Smith, Latin, D, 6
Mrs. Smith, Latin, NA, 2
Mrs. Smith, SAT Prep, A, 1
Mrs. Smith, SAT Prep, C, 4
Mrs. Smith, SAT Prep, D, 2
Mrs. Smith, SAT Prep, NA, 1
Mrs. Smith, NA, C, 7
Mrs. Smith, NA, D, 6
Mrs. Smith, NA, NA, 1", strip.white=TRUE)

最佳答案

您可以使用scale_fill_discrete (不是 scale_color_discrete 因为您在 fill= 中使用了 color= 而不是 aes() )与特定的 limits=drop=值。

ggplot(classes_filtered, aes(x = subject, y = total_students, fill = Grades_Given)) + 
  geom_bar(stat = "identity", colour = "black") + 
  scale_fill_discrete(limits = possible_grades, drop = FALSE) +
  labs(x="Subject", y="Number of Students", fill = "Grade") +
  ggtitle("Grades Given per Subject")

关于r - 将数据集中不存在的值添加到图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63143402/

相关文章:

r - 如何绘制二元混合效果模型以进行视觉呈现

r - 如何在 R 中的谷歌地图上加入 ggplot 点?

r - 如何使用自由刻度但在ggplot中保留固定引用点?

java - rcaller 2.2 和 2.3 不会通过 runAndReturnResultOnline 在顺序命令模式下停止

r - 用线连接图中的中值

R:是否可以在同一列中使用 mutate+lag?

r - 在 R 中的点数据集中选择 n 个最均匀分布的点

r - Phyloseq 中的 ggplot2 对象 - 如何重新排序 x 轴条目?

r - 连字符长度取决于设备类型(pdf、png) - 如何使用 pdf 获得短连字符?

r - 如何调整图例属性以显示2个特征?