问题
I have following data and code:
> mat <- matrix(c(120,230,84,70,130,83,13,26,18),3)
> dimnames(mat) <- list(c("good","fair","poor"),c("a","b","c"))
> mat
> mat
a b c
good 120 70 13
fair 230 130 26
poor 84 83 18
>
> chisq.test(mat)
Pearson's Chi-squared test
data: mat
X-squared = 11.411, df = 4, p-value = 0.02231
> library(vcd)
> mosaic(mat, shade=T)

The chi-squared test shows significant difference but no color is seen since residuals are small. With higher residuals, colors are seen:

?mosaic shows this information:
highlighting_fill: color vector or palette function used for a highlighted variable, if any.
How can I change fill color for above plot?
回答1:
By default, the shading of mosaic plots in vcd
uses the cut-offs 2 and 4 for the absolute value of the residuals associated with each cell as suggested by Friendly (1994, Journal of the American Statistical Association, 89, 190-200). The idea behind this is that these cut-offs should be crossed with approximately 5% and 0.01% if the model fits well (due to the approximate normality of the residuals). However, these cut-offs corresponds to individual significance of the cells while the chi-squared test assesses overall significance.
There are two strategies to deal with this: (1) As the Friendly (1994) shading is intended to bring out the pattern of deviation rather than to correspond directly to significance, one can simply modify the cut-offs to lower values that work well for a given table (e.g., 1 and 1.8 here). (2) Switch to a test of the maximum absolute residuals (rather than their sum of squares) so that all cells that are significant at certain significance levels (e.g., 10% and 1%) can be shaded. Both strategies are implemented in vcd
and illustrated in the examples of ?shading_hcl
(using an example with very similar properties to your mat
). The underlying ideas are explained in Zeileis, Meyer, Hornik (2007). "Residual-Based Shadings for Visualizing (Conditional) Independence", Journal of Computational and Graphical Statistics, 16(3), 507-525. doi:10.1198/106186007X237856
Strategy (1) can be applied to your data by:
mosaic(mat, gp = shading_hcl, gp_args = list(interpolate = c(1, 1.8)))

set.seed(403)
mosaic(mat, gp = shading_max)

回答2:
No really an elegant solution but you can manually define your colours using gpar
mosaic(mat, shade=T, colorize = T, gp = gpar(fill=matrix(c("red","blue","light green", "green", "black","red","brown","white","blue"), 3, 3)))
The next step is to populate the matrix in gpar with sensible colours. There is a pretty good post here about how to assign a colour ramp based on values. https://stackoverflow.com/a/6320940/1502898
来源:https://stackoverflow.com/questions/29837257/how-to-change-color-palette-of-mosaic-plot