Reputation: 247
I am trying to have A, B, C, D AND E in the legend of my geom_bar chart, even if those values do not exist in my dataset. Is there a way to do that in R? Below is the code I currently have...
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")
Along with the dataset I'm working with. Any assistance is truly appreciated. Thanks.
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)
Upvotes: 2
Views: 204
Reputation: 206242
You can use scale_fill_discrete
(not scale_color_discrete
since you used fill=
and not color=
in the aes()
) with specific limits=
and drop=
values.
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")
Upvotes: 4