使用ggplot绘制PSO与PSOA的重叠置信区间(geom_ribbon实现)
Got it, let's walk through how to create that confidence interval plot using geom_ribbon in ggplot2. Your dataset structure (with Meta for algorithm type, prob as your x-variable, plus mean, lowerci, upperci) is perfect for this—here's a step-by-step breakdown:
Step 1: Load Required Packages
First, make sure you have ggplot2 installed and loaded. If you need to tweak your data (like filtering or sorting), dplyr can be a handy addition too:
# Install packages if you haven't already # install.packages(c("ggplot2", "dplyr")) library(ggplot2) library(dplyr) # Optional, but useful for quick data prep
Step 2: Core Plot Code
The plan is to plot the mean values as distinct lines for each algorithm, then overlay the confidence intervals using geom_ribbon. Here's a complete code example tailored to your dataset:
# Replace 'df' with your actual dataset name ggplot(df, aes(x = prob, y = mean, color = Meta)) + # Add confidence ribbon first (so lines sit on top) geom_ribbon(aes(ymin = lowerci, ymax = upperci, fill = Meta), alpha = 0.3, # Semi-transparent to avoid blocking lines color = NA) # Remove ribbon border for cleaner look # Add mean line for each algorithm geom_line(linewidth = 1) + # Customize labels and title labs(title = "Confidence Intervals: PSO vs PSOA", x = "Probability Value", y = "Mean Metric", color = "Algorithm", fill = "Algorithm") + # Clean up the visual theme theme_minimal() + theme(plot.title = element_text(hjust = 0.5))
Key Tips & Customizations
- Layer Order: We add
geom_ribbonbeforegeom_lineso the mean lines are visible above the confidence intervals. - Transparency: Adjust the
alphavalue (0 to 1) to make the intervals more or less prominent—0.3 is a good starting point. - Data Validation: Ensure your
probvariable is numeric (not a factor) so ggplot treats it as a continuous x-axis. If it's a factor, convert it withdf$prob <- as.numeric(as.character(df$prob)). - Handling Gaps: If you have missing data points, add
na.rm = TRUEinsidegeom_ribbonandgeom_lineto skip those entries.
Quick Example with Your Sample Data
Using the snippet you shared, the plot would show:
At
prob = 0.1, PSO’s mean value (6705423) sits in the middle of a ribbon spanning from 9913.939 to 151671.3—with a matching ribbon and line for PSOA at eachprobvalue.
内容的提问来源于stack exchange,提问作者Wagner Jorge

