我正在尝试为一系列生成ggplot
图形的函数编写一些自动化单元测试。
例如,我想为绘图设置特定的色阶。现在我需要一种方法来确定是否实际应用了正确的色标。
的背景:
下面是一些示例代码,将fill
颜色设置为使用 ColourBrewer 调色板Dark2
:
p <- ggplot(mtcars, aes(x=factor(cyl), y=mpg, fill=factor(gear))) +
geom_bar(stat="identity") +
facet_grid(~gear) +
scale_fill_brewer(palette="Dark2")
print(p)
好的,所以目视检查告诉我代码有效。
我试过的:
现在我想通过检查对象来确认这一点:
str(p, max.level=1)
List of 8
$ data :'data.frame': 32 obs. of 11 variables:
$ layers :List of 1
$ scales :Reference class 'Scales' [package "ggplot2"] with 1 fields
..and 20 methods, of which 9 are possibly relevant
$ mapping :List of 3
$ options :List of 1
$ coordinates:List of 1
..- attr(*, "class")= chr [1:2] "cartesian" "coord"
$ facet :List of 9
..- attr(*, "class")= chr [1:2] "grid" "facet"
$ plot_env :<environment: R_GlobalEnv>
- attr(*, "class")= chr "ggplot"
很好,这个$scales
对象看起来很有趣。让我们更详细地看一下:
str(p$scales)
Reference class 'Scales' [package "ggplot2"] with 1 fields
$ scales:List of 1
..$ :List of 14
.. ..$ call : language discrete_scale(aesthetics = "fill", scale_name = "brewer", palette = brewer_pal(type, palette))
.. ..$ aesthetics: chr "fill"
.. ..$ scale_name: chr "brewer"
.. ..$ palette :function (n)
.. ..$ range :Reference class 'DiscreteRange' [package "scales"] with 1 fields
.. .. ..$ range: NULL
.. .. ..and 14 methods, of which 3 are possibly relevant:
.. .. .. initialize, reset, train
.. ..$ limits : NULL
.. ..$ na.value : logi NA
.. ..$ expand : list()
.. .. ..- attr(*, "class")= chr "waiver"
.. ..$ name : NULL
.. ..$ breaks : list()
.. .. ..- attr(*, "class")= chr "waiver"
.. ..$ labels : list()
.. .. ..- attr(*, "class")= chr "waiver"
.. ..$ legend : NULL
.. ..$ drop : logi TRUE
.. ..$ guide : chr "legend"
.. ..- attr(*, "class")= chr [1:3] "brewer" "discrete" "scale"
and 20 methods, of which 9 are possibly relevant:
add, clone, find, get_scales, has_scale, initialize, input, n, non_position_scales
但在这里我画了一个空白。里面没有任何东西p$scales
看起来像我的输入palette
,或者实际上像颜色。
我期望找到的:
我期望的颜色是:
library(RColorBrewer)
brewer.pal(3, name="Dark2")
[1] "#1B9E77" "#D95F02" "#7570B3"
问题:
如何询问ggplot
对象以使用特定的填充颜色?