我似乎无法在ggplot2中设置功能区来显示。
这是一个组成的数据集:
Estimate <- c(100,125,150,175)
GlobalDFData <- data.frame(Estimate, Upper = Estimate + 25, Lower = Estimate - 25, Date = paste0('Q', 1:4,'_16'), Area = 'Global', stringsAsFactors = FALSE)
这是我尝试的代码没有成功。我得到折线图而不是上下界
ggplot(GlobalDFData, aes(x = Date)) +
geom_line(aes(y = Estimate, group = Area, color = Area))+
geom_point(aes(y = Estimate, x = Date))+
geom_ribbon(aes(ymin = Lower, ymax = Upper))
答案 0 :(得分:7)
geom_ribbon
更喜欢连续的x值,但你可以通过在通话期间提供一个来欺骗它。
plt <- ggplot(dat, aes(x = Date)) +
geom_line(aes(y = Estimate, group = Area, color = Area)) +
geom_point(aes(y = Estimate, x = Date))
plt + geom_ribbon(aes(x = 1:length(Date), ymin = Lower, ymax = Upper), alpha = .2)
此外,您可以使用
geom_linerange
,但这可能无法实现您的目标:
plt + geom_linerange(aes(ymin = Lower, ymax = Upper, color = Area))
奇怪的是,使用geom_ribbon
分配颜色可以获得相同(有效)的结果(图中未显示):
plt + geom_ribbon(aes(ymin = Lower, ymax = Upper, color = Area))
此外,您可以使用zoo
包将季度时间转换为可以理解为连续的内容,并与scale_x_yearqtr
结合使用:
library(zoo)
dat$Date <- as.yearqtr(dat$Date, format = 'Q%q_%y')
ggplot(dat, aes(x = Date)) +
scale_x_yearqtr(format = 'Q%q_%y') +
geom_line(aes(y = Estimate, group = Area, color = Area))+
geom_point(aes(y = Estimate, x = Date))+
geom_ribbon(aes(ymin = Lower, ymax = Upper), alpha = 0.2)
答案 1 :(得分:0)
geom_ribbon
需要分组变量。
我们都知道,您需要告诉geom_line
线路需要连接哪些观察。如果每个组只有一个观察值,则可以指定group = 1
。 geom_ribbon
似乎也是如此。这就是为什么在@alexforrence示例中,提供分组美感(color = Area
)会导致输出奇怪的现象,类似于geom_linerange
的原因。
指定group = 1
(有趣的是在aes()
内部或外部)是一种解决方案。无需将x更改为连续变量,也不需要任何动物园魔术。
library(tidyverse)
Estimate <- c(100,125,150,175)
GlobalDFData <- data.frame(Estimate, Upper = Estimate + 25, Lower = Estimate - 25, Date = paste0('Q', 1:4,'_16'), Area = 'Global', stringsAsFactors = FALSE)
plt <- ggplot(GlobalDFData, aes(x = Date)) +
geom_line(aes(y = Estimate, group = Area, color = Area)) +
geom_point(aes(y = Estimate, x = Date))
plt + geom_ribbon(aes(ymin = Lower,
ymax = Upper,
group = 1),
alpha = 0.5)
由reprex package(v0.2.1)于2019-04-24创建