ggplot分面柱状图:如何为不同分数柱子设置专属颜色并添加图例
Custom Column Colors with Consistent Facet Styling in ggplot2
Got it, let's get your bar chart colored correctly across facets with a legend! Here's how to adjust your code step by step:
Key Changes Needed
Instead of using a static fill="skyblue" for all bars, we'll map the fill color directly to your PF.Score variable. Then we'll define custom colors for each score to match your request, and ensure this mapping carries over to your faceted plot.
Modified Code
First, define your custom color palette (adjust the key-value pairs to match all your possible scores):
# Define color mapping for each score - add/remove entries as needed score_colors <- c( "2" = "red", "3" = "blue", "4" = "forestgreen", "5" = "orange" )
Then update your ggplot code to use this mapping:
# Load patchwork if you haven't already (needed for g1+g2 plot combination) if (!require(patchwork)) { install.packages("patchwork") library(patchwork) } # Base plot with color mapping g1 <- ggplot(mydata, aes(x = PF.Score, fill = PF.Score)) + geom_bar(color = "Black") + # Remove static fill here - it's now mapped in aes() geom_text(stat = "count", aes(label = ..count..), size = 4, vjust = -0.3) + ylab("% of Suppliers") + xlab("Score of Suppliers") + ggtitle("Score distribution of suppliers") + theme_classic() + theme(axis.ticks.y = element_blank(), axis.text.y = element_blank()) + # Apply custom colors and set legend title scale_fill_manual(values = score_colors, name = "Supplier Score") # Faceted plot inherits color mapping automatically g2 <- g1 + facet_wrap(~GROUP) # Display both plots side by side g1 + g2
Important Notes
- Color Mapping: By putting
fill = PF.Scoreinsideaes(), ggplot knows to assign colors based on the score values and generate a legend. - Consistent Facet Colors: Since
g2is built fromg1, it uses the exact same color mapping—so the same score will always have the same color across all facets. - Score Data Type: If your
PF.Scoreis a numeric variable instead of character, adjust thescore_colorskeys to numbers (e.g.,2 = "red"instead of"2" = "red"). - Patchwork Package: The
g1 + g2syntax relies on thepatchworkpackage for combining plots—if you haven't used it before, the code above will install and load it for you.
内容的提问来源于stack exchange,提问作者Sourabh_me
相关产品推荐
相关产品推荐

