咨询在R语言中绘制差值图的方法:预期值设为0
Got it, let's break down how to create that deviation plot you're looking for—where the expected value is 0, and we visualize how observed values sit above or below this baseline. I'll cover two popular approaches: base R and ggplot2, so you can pick what fits your workflow best.
First, Let's Create Sample Data
Let's start with some dummy data to work with. We'll make a data frame with categories (like measurements or groups) and their observed values (which are the deviations from 0, since expected is 0):
# Create sample data set.seed(123) # For reproducibility df <- data.frame( Category = paste0("Group_", 1:8), Observed = rnorm(8, mean = 0, sd = 2) # Random values around 0 )
Option 1: Base R Plot
Base R is great for quick, straightforward plots. Here's how to make a bar plot with a clear baseline at 0, and color-coded bars for positive/negative deviations:
# Calculate color based on deviation direction bar_colors <- ifelse(df$Observed > 0, "#2ecc71", "#e74c3c") # Create the bar plot barplot(df$Observed, names.arg = df$Category, col = bar_colors, ylim = c(min(df$Observed)-0.5, max(df$Observed)+0.5), # Fit all values main = "Observed Deviations from Expected Value (0)", ylab = "Deviation from Baseline", xlab = "Category", las = 2 # Rotate x-axis labels for readability ) # Add a horizontal line at 0 (the expected value) abline(h = 0, lwd = 2, lty = 2, col = "#34495e") # Optional: Add value labels on top of bars text(x = 1:length(df$Category), y = df$Observed + ifelse(df$Observed > 0, 0.2, -0.2), labels = round(df$Observed, 2), col = "white", font = 2)
What this does:
- We color positive deviations green and negative ones red for quick visual distinction.
- The
ylimensures all bars fit in the plot area, even the extreme values. - The dashed line at
h=0clearly marks the expected baseline. - Value labels make it easy to read exact deviation numbers.
Option 2: ggplot2 (More Customizable)
If you want a more polished, customizable plot, ggplot2 is the way to go. Here's a similar plot with cleaner styling:
library(ggplot2) ggplot(df, aes(x = Category, y = Observed, fill = Observed > 0)) + geom_col(width = 0.7) + geom_hline(yintercept = 0, linetype = "dashed", color = "#34495e", linewidth = 1) + geom_text(aes(label = round(Observed, 2)), vjust = ifelse(df$Observed > 0, -0.5, 1.5), color = "white", fontface = "bold") + scale_fill_manual(values = c("#e74c3c", "#2ecc71"), labels = c("Below Expected", "Above Expected"), name = "Deviation Direction") + labs(title = "Observed Deviations from Expected Value (0)", y = "Deviation from Baseline", x = "Category") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1), plot.title = element_text(hjust = 0.5))
Key customizations here:
- The
fillaesthetic automatically maps positive/negative deviations to colors, with a legend explaining what each means. theme_minimalgives a clean, modern look, and we rotate x-axis labels for readability.- The text labels are positioned correctly above/below bars depending on deviation direction.
Adjustments for Your Exact Data
If your observed values are calculated as (observed - expected) where expected is 0, you can just use the observed values directly (since observed - 0 = observed). If your expected value was something else, you'd first compute df$Deviation <- df$Observed - df$Expected, then plot Deviation instead.
Feel free to tweak colors, labels, or plot type (e.g., use geom_point() instead of geom_col() for a scatter-style deviation plot) to match your example exactly!
内容的提问来源于stack exchange,提问作者theadleb

