R ggpairs 更改对角线上条形直方图的颜色

问题描述

我想更改成对图上直方图条形的颜色,从而为每个变量设置不同的颜色。看来我可以通过将“fill =”选项更改为新颜色来更改所有对角直方图的颜色,但是当我尝试替换四种颜色的列表时,我收到错误报告:

"r: Aesthetics 必须是长度为 1 或与数据相同 (15): 填充"

所以颜色似乎与为直方图指定的 bin 数量有关,而不是每个直方图的填充颜色?

为对角线上的每个直方图实现不同颜色的最佳方法是什么?

示例代码如下:

require(Ggally)

# function for scatter plots with smoothed trend line
lower_plots <- function(data,mapping,...) {
  ggplot(data = data,mapping = mapping) +
    geom_point(color = "black",shape = 1,size = 1,alpha = 1) +
    geom_smooth(method = "gam",...) 
} 

# colour palette for histograms - subsitue for fill = ?
clrs <- c("red","green","blue","orange")

# pairs plot
ggpairs(iris,1:4,diag = list(continuous = wrap("barDiag",bins = 15,fill = "blue")),lower = list(continuous = wrap(lower_plots,color="red",se=F))) +
  theme_light(base_size = 12) +                                                                                                                 
  theme_light(base_size = 12) +                                                                                                                 
  scale_fill_manual(values = ZNS[order(ZNS$Zone),4])  +                                                                                         
  theme(panel.grid.minor = element_blank(),panel.grid.major = element_blank()) +
  theme(plot.margin = unit(c(2.5,2.5,3.5),"lines")
  ) 

enter image description here

解决方法

我通过在函数内部使用全局赋值找到了解决您问题的方法。首先,我认为这是不可能的,因为缺乏能够在输入的一列中识别如何为直方图着色,因为每行都包含多个观察结果......我测试了一下并想知道,考虑到一切的事实分批/循环处理,全局分配会有所帮助 - 确实如此:

require(GGally)

# function for scatter plots with smoothed trend line
lower_plots <- function(data,mapping,...) {
    ggplot(data = data,mapping = mapping) +
        geom_point(color = "black",shape = 1,size = 1,alpha = 1) +
        geom_smooth(method = "gam",...) 
} 

# working with a trick of global assignment
diag_plots <- function(data,...) {
    # increase counter each run globally so outside the function as well and this does the trick!
    x <<- x + 1
    ggplot(data = data,mapping = mapping) +
        # choose color by counter and send bin width argument in
        geom_histogram(fill = clrs[x],...)
} 

# set the color and counter
clrs <- c("red","green","blue","orange")
x <- 0

# pairs plot
ggpairs(iris,1:4,diag = list(continuous = wrap(diag_plots,bins = 15)),lower = list(continuous = wrap(lower_plots,color="red",se=FALSE))) +
        theme_light(base_size = 12) + 
        theme_light(base_size = 12) + 
        theme(panel.grid.minor = element_blank(),panel.grid.major = element_blank()) +
    theme(plot.margin = unit(c(2.5,2.5,3.5),"lines")) 

enter image description here