[R] colored table

Michael Friendly friendly at yorku.ca
Sun May 29 17:01:14 CEST 2016


Hi Naresh

If you want to make a graphic of the table, with the frequencies printed 
in the cells try a mosaic plot from the vcd package

library(vcd)
mosaic(HairEyeColor[,,1], shade = TRUE, legend=FALSE, 
labeling=labeling_values)

or to make cell sizes proportional to expected frequencies,

mosaic(HairEyeColor[,,1], shade = TRUE, legend=FALSE, 
labeling=labeling_values, type="expected")

You can also use ggplot2::geom_tile() for something that is a more 
direct version of a table or a heatmap, with shaded backgrounds, and 
geom_text()
to print the values.

 From an non-reproducible example of mine, where cells are filled
with a unidimensional range of colors from white to blue, and
the text is printed in black, until the background gets too dark:

p <- ggplot(ht2, aes(decade, variable)) +
       geom_tile(aes(fill = Freq), color = "white") +
       scale_fill_gradient(low = "white", high = "blue") +
       geom_text(aes(fill = Freq, label = Freq),
                 colour = ifelse(ht2$Freq > 40, "white", "black")) +
       labs(title = "Keyword Occurrences by Topic and Year",
            x = "Decade", y = "Keyword")

In contrast to what someone else expressed, for some purposes --- where 
you want to show the _pattern_ of values in a table directly, colored 
backgrounds, if done judiciously can be extremely useful to show the 
viewer what is important.

-Michael

On 5/28/2016 9:10 AM, Naresh Gurbuxani wrote:
> I want to print a table where table elements are colored according to the frequency of the bin.  For example, consider below table.
>
> Function values that I would like to print in the table
>
>                             x.eq.minus1  x.eq.zero  x.eq.plus1
> y.eq.minus1             -20                 10            -5
> y.eq.zero                 -10                  6             22
> y.eq.plus1                -8                    10           -14
>
>
> Frequency table to color the above table
>
>                             x.eq.minus1  x.eq.zero  x.eq.plus1
> y.eq.minus1             0.05             0.15           0.1
> y.eq.zero                 0.07             0.3           0.08
> y.eq.plus1                0.05            0.15           0.05
>
>
> In the resulting table, the element for (x = 0, y = 0) will be 6.  This will be printed with a dark color background.  The element for (x = -1, y = -1) will be -20.  This will be printed with a light color background.  And so on.
>
> Thanks for your help,
> Naresh
>


-- 
Michael Friendly     Email: friendly AT yorku DOT ca
Professor, Psychology Dept. & Chair, Quantitative Methods
York University      Voice: 416 736-2100 x66249 Fax: 416 736-5814
4700 Keele Street    Web:   http://www.datavis.ca
Toronto, ONT  M3J 1P3 CANADA



More information about the R-help mailing list