ggplot2中缺少功能区 [英] Missing Ribbon in ggplot2

查看:115
本文介绍了ggplot2中缺少功能区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎在ggplot2中设置要显示的功能区时遇到麻烦.

I seem to be having trouble setting up a ribbon in ggplot2 to display.

这是一个伪造的数据集:

Here's a made up data set:

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)

这是我正在尝试的代码,但没有成功.我得到了折线图,但没有上限和下限

Here's the code that I'm trying with no success. I get the line chart but not the upper and lower bounds

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))

推荐答案

geom_ribbon首选连续x值,但是您可以在调用过程中提供一个x值来欺骗它.

geom_ribbon prefers a continuous x value, but you can trick it a bit by providing one during the call.

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,但这可能无法实现您想要的外观:

Additionally, you could use geom_linerange, but that probably doesn't achieve the look you're going for:

plt + geom_linerange(aes(ymin = Lower, ymax = Upper, color = Area))

奇怪的是,用geom_ribbon分配颜色可以达到相同的(有效的)结果(图未显示):

And curiously enough, assigning a color with geom_ribbon achieves the same (effective) result (plot not shown):

plt + geom_ribbon(aes(ymin = Lower, ymax = Upper, color = Area))


此外,您可以结合使用zoo包和scale_x_yearqtr,将季度时间转换为可以理解为连续的时间:


Additionally, you could use the zoo package to convert your quarterly times to something that can be understood as continuous, in conjunction with 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)

这篇关于ggplot2中缺少功能区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆