You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

ggplot2绘图报错:object 'variable' not found,求R语言绘图解决方案

Fixing the "object 'variable' not found" Error in ggplot2

Hey there, let's break down why you're hitting that error and get your plot working smoothly!

The Root Cause

Looking at your head(mdat) output, you'll notice all your data is crammed into a single column named day..variable..value. That's because you used sep="\t" (tab delimiter) when reading your CSV, but your actual data is separated by commas (e.g., Day 0, Actinobacteria,0.187). Since R couldn't split the data into separate columns, it has no idea what variable, day, or value are—hence the "object not found" error.

Step-by-Step Fix

  1. Correctly Read Your Data
    First, fix the read.csv call to use the right delimiter. Since your data uses commas, you can either explicitly set sep="," or just rely on read.csv's default (it uses commas by default):

    library(reshape2)
    library(ggplot2)
    
    # Read with correct comma delimiter
    mdat <- read.csv(file = "~/Desktop/final_data/low_group.csv", header = TRUE)
    
    # Optional: If column names still look wonky, manually rename them
    colnames(mdat) <- c("day", "variable", "value")
    
  2. Verify Your Data Structure
    Run str(mdat) to confirm you have three distinct columns:

    • day: Character/factor (e.g., "Day 0", "Day 3")
    • variable: Character/factor (e.g., "Actinobacteria", "Bacteroidetes")
    • value: Numeric (the abundance values)
  3. Plot with ggplot2
    Now that your columns are properly separated, your original plot code will work. Here's a polished version with clear labels and a clean theme:

    ggplot(mdat, aes(x = variable, y = value, fill = day)) +
      geom_bar(stat = "identity", position = "stack") + # Stacked bars (default, but explicit is clear)
      labs(
        title = "Microbial Relative Abundance by Day",
        x = "Microbial Phylum",
        y = "Relative Abundance",
        fill = "Sampling Day"
      ) +
      theme_bw() +
      theme(axis.text.x = element_text(angle = 45, hjust = 1)) # Rotate x-axis labels for readability
    

Quick Tips for Future Plots

  • Always double-check your data's delimiter before reading it into R (commas, tabs, and spaces are the most common).
  • Use str(mdat) or summary(mdat) to confirm your variables are the right type (numeric columns shouldn't be stored as characters!).

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

火山引擎 最新活动