带有字符xintercept的geom_vline [英] geom_vline with Character xintercept
问题描述
我有一些ggplot代码,在0.8.9中可以正常工作,但不在0.9.1中。
我将绘制 theDF
,并希望在 xintercept =2010 Q1处绘制垂直线。
theGrid
仅用于创建 theDF
。
theGrid < - expand.grid(2009:2011,1:4)
theDF< - data.frame(YrQtr = sprintf(%s Q%s,theGrid $ Var1,theGrid $ Var2),
Minutes = c(1000,2200,1450,1825,1970,1770,1640,1920,1790,1800,1750,1600))
使用的代码是:
g < - ggplot(theDF,aes(x = YrQtr, y =分钟))+
geom_point()+
opts(axis.text.x = theme_text(angle = 90))
g + geom_vline(data = data.frame这个工作正常,但是它的工作原理很简单,只需要一个点就可以了。 R 2.13.2与ggplot2 0.8.9,但不在R 2.14+与ggplot2 0.9.1。
解决方法是:
g + geom_vline(data = data.frame(Vert = 4),aes(xintercept = Vert))
但这不是我的问题的好解决方案。
也许与 scale_x_discrete
可能有助于解决问题吗?
可以试试这个:
g + geom_vline(aes(xintercept = which(levels(YrQtr)%in%'2010 Q1') ))
这样可以避免为所选因子级别创建虚拟数据框。 which()命令返回索引(或者索引,如果%运算符中%右侧是一个向量)因子级别[s]与vlines关联。
对此的一个警告是,如果某些类别没有出现在您的数据中,并且您在比例中使用 drop = TRUE
,则线条不会显示在正确的地方。
I have some ggplot code that worked fine in 0.8.9 but not in 0.9.1.
I am going to plot the data in theDF
and would like to plot a vertical line at xintercept="2010 Q1."
theGrid
is merely used to create theDF
.
theGrid <- expand.grid(2009:2011, 1:4)
theDF <- data.frame(YrQtr=sprintf("%s Q%s", theGrid$Var1, theGrid$Var2),
Minutes=c(1000, 2200, 1450, 1825, 1970, 1770, 1640, 1920, 1790, 1800, 1750, 1600))
The code used is:
g <- ggplot(theDF, aes(x=YrQtr, y=Minutes)) +
geom_point() +
opts(axis.text.x=theme_text(angle=90))
g + geom_vline(data=data.frame(Vert="2010 Q2"), aes(xintercept=Vert))
Again, this worked fine in R 2.13.2 with ggplot2 0.8.9, but does not in R 2.14+ with ggplot2 0.9.1.
A workaround is:
g + geom_vline(data=data.frame(Vert=4), aes(xintercept=Vert))
But that is not a good solution for my problem.
Maybe messing around with scale_x_discrete
might help?
You could try this:
g + geom_vline(aes(xintercept = which(levels(YrQtr) %in% '2010 Q1')))
This avoids the need to create a dummy data frame for the selected factor level. The which() command returns the index (or indices if the right side of the %in% operator is a vector) of the factor level[s] to associate with vlines.
One caution with this is that if some of the categories do not appear in your data and you use drop = TRUE
in the scale, then the lines will not show up in the right place.
这篇关于带有字符xintercept的geom_vline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!