You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Color Mapping: By putting fill = PF.Score inside aes(), ggplot knows to assign colors based on the score values and generate a legend.
  2. Consistent Facet Colors: Since g2 is built from g1, it uses the exact same color mapping—so the same score will always have the same color across all facets.
  3. Score Data Type: If your PF.Score is a numeric variable instead of character, adjust the score_colors keys to numbers (e.g., 2 = "red" instead of "2" = "red").
  4. Patchwork Package: The g1 + g2 syntax relies on the patchwork package for combining plots—if you haven't used it before, the code above will install and load it for you.

内容的提问来源于stack exchange,提问作者Sourabh_me

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 17:32:37