ggplot2 facet_wrap geom_text不接受日期值

时间:2016-05-04 19:15:59

标签: r ggplot2 geom-text

我有一个小的数据集,本地,(5个观察)有两种类型:a和b。 每个观察都有一个日期字段(p.start),比率和持续时间。

local

  principal    p.start duration allocated.days    ratio
1         P 2015-03-18        1       162.0000 162.0000
2         V 2015-08-28        4        24.0000   6.0000
3         V 2015-09-03        1        89.0000  89.0000
4         V 2015-03-30        1        32.0000  32.0000
5         P 2015-01-29        1       150.1667 150.1667

str(local)

'data.frame':   5 obs. of  5 variables:
 $ principal     : chr  "P" "V" "V" "V" ...
 $ p.start       : Date, format: "2015-03-18" "2015-08-28" "2015-09-03" "2015-03-30" ...
 $ duration      : Factor w/ 10 levels "1","2","3","4",..: 1 4 1 1 1
 $ allocated.days: num  162 24 89 32 150
 $ ratio         : num  162 6 89 32 150

我有另一个数据框,统计数据,文本要添加到分面图。

stats

  principal         xx    yy            zz
1         P 2015-02-28 145.8 Average = 156
2         V 2015-02-28 145.8  Average = 24

str(stats)

'data.frame':   2 obs. of  4 variables:
 $ principal: chr  "P" "V"
 $ xx       : Date, format: "2015-02-28" "2015-02-28"
 $ yy       : num  146 146
 $ zz       : chr  "Average = 156" "Average = 24"

以下代码失败:

p     = ggplot (local, aes (x = p.start, y = ratio, size = duration))
p     = p + geom_point (colour = "blue"); p
p     = p + facet_wrap (~ principal, nrow = 2); p
p     = p + geom_text(aes(x=xx, y=yy, label=zz), data= stats)
p
Error: Continuous value supplied to discrete scale

有什么想法吗?我错过了一些明显的东西。

2 个答案:

答案 0 :(得分:1)

问题在于您正在绘制2个data.frames,但您的初始ggplot调用包含aes参数仅涉及local data.frame。

因此,虽然您的geom_text指定了data=stats,但它仍然在寻找size=duration

以下内容适用于我:

ggplot(local) +
  geom_point(aes(x=p.start, y=ratio, size=duration), colour="blue") +
  facet_wrap(~ principal, nrow=2) +
  geom_text(data=stats, aes(x=xx, y=yy, label=zz))

答案 1 :(得分:1)

只需从size = duration移除ggplot (local, aes (x = p.start, y = ratio, size = duration)),然后将其添加到geom_point (colour = "blue")即可。然后,它应该工作。

ggplot(local, aes(x=p.start, y=ratio))+
geom_point(colour="blue", aes(size=duration))+
facet_wrap(~principal, nrow=2)+
geom_text(aes(x=xx, y=yy, label=zz), data=stats)

enter image description here