R语言geom_bar图例中的‘n’框是什么?如何单独移除?
First, let's break down what that 'n' legend box means:
The 'n' entry in your legend is almost certainly tied to an unexpected value in your Group.2 column. Looking at your data structure, your Group.2 factor is defined with levels: "Radio", "Video", "Engineering", "800Mhz", "PSSRP", "Other" — so the 'n' is either:
- A data entry error where some rows have
Group.2set to the string "n" instead of one of the valid levels, or - A display quirk for missing values (NA) in your
Group.2column (in rare cases, locale settings or older ggplot versions might render NA as "n").
To confirm the exact cause, run this quick check to see all values in Group.2:
table(HrSums$Group.2, useNA = "always")
This will show you the count of each category, including any NA values or unexpected entries like "n".
How to Remove Only the 'n' Legend Box (Keep Other Legends)
You have a few straightforward options depending on whether you want to clean your data first or adjust the plot directly:
Option 1: Clean the Data First (Recommended)
Filter out the rows with the unwanted 'n' (or NA) value before plotting:
# If 'n' is a literal string value HrSums_clean <- HrSums[HrSums$Group.2 != "n", ] # If it's an NA value HrSums_clean <- HrSums[!is.na(HrSums$Group.2), ] # Now plot with the cleaned data ggplot(data = HrSums_clean, aes(x = Group.1, y = x, fill = Group.2)) + geom_bar(stat = "sum", position = position_stack(reverse = TRUE)) + coord_flip() + labs(title = "Hours Billed, by Technician and Shop", y = "Hours Billed", x = "Technician", fill = "Shop")
Option 2: Adjust the Plot to Exclude the 'n' Legend
If you don't want to modify your original dataset, you can explicitly tell ggplot which legend items to display using scale_fill_discrete():
ggplot(data = HrSums, aes(x = Group.1, y = x, fill = Group.2)) + geom_bar(stat = "sum", position = position_stack(reverse = TRUE)) + coord_flip() + # List only the valid Group.2 levels you want to keep in the legend scale_fill_discrete(breaks = c("800Mhz", "Engineering", "Other", "PSSRP", "Radio", "Video")) + labs(title = "Hours Billed, by Technician and Shop", y = "Hours Billed", x = "Technician", fill = "Shop")
If the 'n' is actually a stand-in for NA values, you can hide NA from the legend directly with:
ggplot(data = HrSums, aes(x = Group.1, y = x, fill = Group.2)) + geom_bar(stat = "sum", position = position_stack(reverse = TRUE)) + coord_flip() + scale_fill_discrete(na.translate = FALSE) + labs(title = "Hours Billed, by Technician and Shop", y = "Hours Billed", x = "Technician", fill = "Shop")
内容的提问来源于stack exchange,提问作者Mark Bunster

