2

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

“r:美学必须是长度1或与数据相同(15):填充”

因此,颜色似乎以某种方式与为直方图指定的箱数而不是每个直方图的填充颜色相关联?

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

下面的示例代码:

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,2.5,3.5), "lines")
  ) 

在此处输入图像描述

4

1 回答 1

2

我通过在函数内部使用全局分配找到了解决您问题的方法。首先,我虽然无法在输入的一列中识别如何为直方图着色,因为每一行都包含多个观察结果......我测试了一下并想知道,鉴于一切的事实批量/循环处理,全局分配会有所帮助 - 它确实:

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, mapping, ...) {
    # 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,2.5,3.5), "lines")) 

在此处输入图像描述

于 2021-07-28T02:43:33.040 回答