我有一些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=Minutes)) +
geom_point() +
opts(axis.text.x=theme_text(angle=90))
g + geom_vline(data=data.frame(Vert="2010 Q2"), aes(xintercept=Vert))
再次,在ggplot2 0.8.9的R 2.13.2中,它可以正常工作,但在ggplot2 0.9.1的R 2.14+中,它却不能。
解决方法是:
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()命令返回要与vlines关联的因子水平的索引(如果%in%运算符的右侧是向量,则返回索引)。
请注意,如果某些类别没有出现在您的数据中,而您在比例尺中使用了
drop = TRUE
,则这些行将不会显示在正确的位置。关于r - 带有字符xintercept的geom_vline,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11093248/