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

ggplot2绘制的柱状图呈灰色无彩色,求排查解决方法

Fixing Gray Bar Issue in ggplot2 Bar Chart

Hey there, let's work through why your bars are showing up gray instead of colored. The main issues are related to how you're mapping color/fill aesthetics and misconfigured scale settings. Here's the breakdown and corrected code:

Step 1: Correctly Prepare Your Melted Data

First, let's ensure your dataset is properly converted to long format (since you referenced eight_gen_scatter_melted). Using reshape2::melt() or tidyr::pivot_longer():

# Load required libraries
library(ggplot2)
library(reshape2) # Or use tidyr if preferred

# Original dataset
eight_gen_scatter <- data.frame(
  pro = c("CONCOCT", "MetaBAT", "MaxBin", "MyCC"),
  MEGAHIT = c(3, 3, 3, 3),
  RayMeta = c(3, 2, 1, 4),
  SPAdes = c(3, 3, 2, 3),
  Velvet = c(3, 3, 0, 2)
)

# Melt into long format with clear column names
eight_gen_scatter_melted <- melt(eight_gen_scatter, id.vars = "pro", 
                                 variable.name = "Assembler", 
                                 value.name = "Value")

Step 2: Fix the ggplot Code

Your original code used color=Programas (likely a typo for pro from your dataset) but color only controls bar outlines—not the fill. To color the interior of bars, use fill instead. We'll also fix the scale configuration to align with your actual data:

ggplot(eight_gen_scatter_melted, aes(x = Assembler, y = Value, fill = pro)) +
  geom_bar(stat = "identity", position = "dodge") +
  # Configure fill scale to match your program names
  scale_fill_discrete(
    name = "Program", # Legend title
    breaks = c("CONCOCT", "MetaBAT", "MaxBin", "MyCC"),
    labels = c("CONCOCT", "MetaBAT", "MaxBin", "MyCC") # Optional if names are already correct
  ) +
  scale_y_continuous(limits = c(0, 8)) +
  labs(x = "Assembler", y = "Value") # Add clear axis labels

Key Fixes Explained:

  • fill=pro instead of color=Programas: Maps your program names to the bar fill color (this was the primary reason bars were gray—no fill aesthetic was mapped).
  • Corrected scale configuration: The scale_fill_discrete now references the actual values in the pro column instead of numeric breaks, ensuring the legend matches your programs.
  • Readable column names: Renamed melted columns to Assembler and Value for clarity (adjust these if your melted data uses different names).

If you want colored outlines for the bars too, add color=pro to the aes alongside fill=pro.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:02:58