ggplot2绘制的柱状图呈灰色无彩色,求排查解决方法
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=proinstead ofcolor=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_discretenow references the actual values in theprocolumn instead of numeric breaks, ensuring the legend matches your programs. - Readable column names: Renamed melted columns to
AssemblerandValuefor 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

