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

如何在R中绘制多层级图表?复现《AppliedPredictiveModeling》指定图表

Replicating the 4x4 Faceted Plot from Applied Predictive Modeling

Got it, let's tackle this plot replication from Applied Predictive Modeling! I'll walk you through how to recreate this 4x4 grid of plots using R (a go-to tool for this book's examples) with ggplot2, which is perfect for this kind of structured visualization.

Step 1: Prepare Your Data

First, you'll need a dataset that includes these variables:

  • x: The x-axis variable for every subplot
  • y: The y-axis variable for each curve
  • sigma: A variable with 4 distinct values (one per curve in each subplot)
  • cost: A variable with 4 distinct values (one per column of subplots)
  • epsilon: A variable with 4 distinct values (one per row of subplots)

If you don't have the exact data yet, here's a sample script to generate a matching structure (swap out the y calculation with your actual data logic):

library(ggplot2)
library(dplyr)

# Set seed for reproducible results
set.seed(42)

# Define parameter values (match your actual data's ranges)
sigma_vals <- c(0.1, 0.5, 1.0, 2.0)
cost_vals <- c(1, 5, 10, 20)
epsilon_vals <- c(0.01, 0.05, 0.1, 0.2)

# Create all combinations of parameters + x values
plot_data <- expand.grid(
  x = seq(0, 10, length.out = 100),
  sigma = sigma_vals,
  cost = cost_vals,
  epsilon = epsilon_vals
)

# Generate y values (replace this with your real data's formula)
plot_data <- plot_data %>%
  mutate(y = sin(x) + sigma * rnorm(nrow(.)) + epsilon * x + (cost / 10))

Step 2: Build the Faceted Plot

This code will generate the 16-subplot grid exactly as you described:

ggplot(plot_data, aes(x = x, y = y, color = factor(sigma))) +
  # Draw 4 distinct curves per subplot (one per sigma)
  geom_line(linewidth = 1) +
  # Create 4x4 grid: rows = epsilon values, columns = cost values
  facet_grid(epsilon ~ cost, labeller = label_both) +
  # Customize legend and axis labels
  scale_color_discrete(name = "Sigma") +
  labs(x = "X Axis", y = "Y Axis") +
  # Clean up theme for readability
  theme_bw() +
  theme(
    strip.background = element_rect(fill = "#f0f0f0"),
    legend.position = "bottom",
    legend.box = "horizontal"
  )

Quick Notes to Match Your Target Plot:

  • facet_grid(epsilon ~ cost) ensures rows map to epsilon values and columns map to cost values, creating the 4x4 layout.
  • color = factor(sigma) assigns a unique color to each sigma value, so you get 4 distinct lines in every subplot.
  • Swap out the simulated y calculation with your actual dataset's logic to replicate the original curves perfectly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:53:37