0

我有一个数据框,我想知道如何使用“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

4

2 回答 2

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为 Date 类,以便自动生成 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

于 2017-04-25T04:11:03.167 回答
1

也许您正在寻找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)

如果您想从第一个数据点开始并从左端删除多余的空间,您可以设置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))

在此处输入图像描述

于 2017-04-25T03:43:55.233 回答