r语言 - ggplot - annotate() - "Discrete value supplied to continuous scale"



我已经阅读了许多关于可能导致错误"向连续刻度提供离散值"的 SO 答案,但我仍然无法解决以下问题。就我而言,错误是由使用annotate()引起的。如果摆脱+ annotate(...)一切正常。否则将引发错误。

我的代码如下:

base <- ggplot() + 
annotate(geom = "rect", ymin = -Inf , ymax = 0, xmax = 0, xmin = Inf, alpha = .1)
annotated <- base + 
geom_boxplot(outlier.shape=NA, data = technicalsHt, aes(x = name, y = px_last))
> base  # fine
> annotated
Error: Discrete value supplied to continuous scale

不幸的是,我无法给出导致此处使用的数据帧的代码(即。technicalsHt)因为它很长并且依赖于APis。它的描述:

> str(technicalsHt)
'data.frame':   512 obs. of  3 variables:
$ date   : Date, format: "2016-11-14" "2016-11-15" ...
$ px_last: num  1.096 0.365 -0.067 0.796 0.281 ...
$ name   : Factor w/ 4 levels "Stock Price Strength",..: 1 1 1 1 1 1 1 1 1 1 ...
> head(technicalsHt)
date     px_last                 name
1 2016-11-14  1.09582090 Stock Price Strength
2 2016-11-15  0.36458685 Stock Price Strength
3 2016-11-16 -0.06696111 Stock Price Strength
4 2016-11-17  0.79613481 Stock Price Strength
5 2016-11-18  0.28067475 Stock Price Strength
6 2016-11-21  1.10780834 Stock Price Strength

没有annotate的代码可以完美运行:

base <- ggplot() 
annotated <- annotated + 
geom_boxplot(outlier.shape=NA, data = technicalsHt, aes(x = name, y = px_last))
> annotated   # fine

我尝试玩弄technicalsHt,例如执行以下操作:

technicalsHt[,3] <- "hi"
technicalsHt[,2] <- rnorm(ncol(technicalsHt), 2,3)

但无论如何,使用annotate语句都会引发错误。

编辑:按照下面的答案,我试图将dataaes放在最初的ggplot调用中,并从一开始就geom_boxplot

base <-                                  
# also tried: base <- ggplot(data = technicalsHt, aes(x = factor(name), y = px_last)) + geom_boxplot(outlier.shape=NA)
annotated <- base + ggplot(data = technicalsHt, aes(x = name, y = px_last)) + geom_boxplot(outlier.shape=NA)
annotate(geom = "rect", ymin = -Inf , ymax = 0, xmax = 0, xmin = Inf, alpha = .1)

这有效,但并不真正令人满意,因为注释层(坐标系的阴影部分)随后覆盖了框。

(例如,该链接也提到了与annotate相关的此错误,但那里给出的答案并不能解决我的问题,因此我将非常感谢您的帮助。首先,哪个变量导致了问题?

我遇到了这个问题,但没有找到我想要的答案,所以这是我的解决方案。这比绘制两倍的箱线图要漂亮一些。

如果要在存在离散比例时注释点下方的矩形,则需要将其指定为 ggplot

ggplot(mtcars, aes(factor(cyl), mpg)) + 
scale_x_discrete() +
annotate(geom = "rect", ymin = -Inf , ymax = 10, xmax = 0, xmin = Inf, alpha = .1) +
geom_boxplot()

切换顺序,将数据和主要美学带入您的ggplot调用中。你基本上是在写这个:

p1 <- ggplot() +
annotate(geom = "rect", ymin = -Inf , ymax = 10, xmax = 0, xmin = Inf, alpha = .1)

此时,p1有一个连续的 x 轴,因为您在此处提供了数字。

p2 <- p1 + geom_boxplot(aes(factor(cyl), mpg), mtcars)

现在,您添加另一个具有离散轴的图层,这将产生错误。

如果你用"正确"的方式写它,一切都很好:

ggplot(mtcars, aes(factor(cyl), mpg)) + 
geom_boxplot() +
annotate(geom = "rect", ymin = -Inf , ymax = 10, xmax = 0, xmin = Inf, alpha = .1)

p.s.:如您所见,制作一个可重现的最小示例来准确显示您的问题并不难。

为了响应分层,我发现的最简单的解决方法是简单地绘制相同的箱形图两次。我知道这是不必要的代码,但它是分层问题的非常快速的解决方案。

ggplot(mtcars, aes(factor(cyl), mpg)) + 
geom_boxplot() +
annotate(geom = "rect", ymin = -Inf , ymax = 10, xmax = 0, xmin = Inf, alpha = .1) + 
geom_boxplot()

由于像素完全重叠,我无法注意到它的任何图像退化。如果有人有UHD显示器,请随时纠正我。

相关内容

最新更新