我试图在 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/