如何在 R 中使用 ggplot2 绘制场面积图

How to draw a field area plot using ggplot2 in R

我有一个数据框,我想知道如何使用 "max"(红色)和填充区域(蓝色)绘制一条线,然后使用 "min" 添加第二条线(绿色)。非常感谢。 x 轴是 "x".

df <- data.frame(
    x = c("Jan","Feb","Mar","April","May","June","July"),
    max = c(100,150,200,300,80,130,50),
    min = c(30,20,40,25,15,10,8))

我试过以下代码:

df$x = 1:7
ggplot(df, aes(x)) + 
    geom_line(aes(y = max), color="red") + 
    geom_area() + 
    geom_line(aes(y = min), color = "blue")

但是出现错误:Error in eval(expr, envir, enclos) : object 'y' not found

也许您正在寻找 geom_ribbon:

df <- data.frame(
    x = c("Jan","Feb","Mar","April","May","June","July"),
    max = c(100,150,200,300,80,130,50),
    min = c(30,20,40,25,15,10,8))

df$xpos <- seq_len(nrow(df))

ggplot(df, aes(x = xpos)) +
    geom_ribbon(aes(ymin = min, ymax = max), fill = 'blue') +
    geom_line(aes(y = max), color = 'red') +
    geom_line(aes(y = min), color = 'green') +
    scale_x_continuous(breaks = df$xpos, labels = df$x)

如果你想从第一个数据点开始并从左端删除多余的space,你可以设置expand = c(0, 0)。但是,您还需要手动扩展右限制以避免 x 标签被裁剪。

ggplot(df, aes(x = xpos)) +
    geom_ribbon(aes(ymin = min, ymax = max), fill = 'blue') +
    geom_line(aes(y = max), color = 'red') +
    geom_line(aes(y = min), color = 'green') +
    scale_x_continuous(breaks = df$xpos, labels = df$x,
                       expand = c(0, 0), limits = c(1, 7.2))

一个选项是将 x 转换为具有正确顺序级别的因素并设置组审美:

library(ggplot2)

df = data.frame(x = c("Jan","Feb","Mar","April","May","June","July"),
                max = c(100,150,200,300,80,130,50), 
                min = c(30,20,40,25,15,10,8))

df$x <- factor(df$x, df$x, ordered = TRUE)

ggplot(df, aes(x, ymin = min, ymax = max, group = 1)) + 
  geom_ribbon(fill = 'steelblue3', alpha = 0.5) + 
  geom_line(aes(y = min), color = 'green3') + 
  geom_line(aes(y = max), color = 'red2')

一个更可靠的选择是将 x 解析为日期 class,以便自动生成 x 轴标签:

df = data.frame(x = c("Jan","Feb","Mar","April","May","June","July"),
                max = c(100,150,200,300,80,130,50), 
                min = c(30,20,40,25,15,10,8))

df$x <- as.Date(paste(substr(df$x, 1, 3), '01 2017'), format = '%b %d %Y')

ggplot(df, aes(x, ymin = min, ymax = max)) + 
  geom_ribbon(fill = 'steelblue3', alpha = 0.5) + 
  geom_line(aes(y = min), color = 'green3') + 
  geom_line(aes(y = max), color = 'red2')

可以使用 scale_x_date 添加更多的分隔符或替代格式。