Search code examples
rcolorsdataframeperformanceanalytics

R - How to conditionally color the values of a data.frame and make a plot


I have this dataframe created with the function table.CalendarReturns from the PerfomanceAnalytics package (the rownames are the years and the colnames are the months ):

tabRet

> 
 gen  feb  mar  apr  may  jun  jul  aug sep  oct nov  dec System
 2004 0.0  3.5  2.9  2.0  1.1 -0.4  1.2 3.3  0.9 1.8  3.0 -0.6   20.1
 2005 1.6  2.3 -1.2  4.0  0.0  1.6 -1.4 2.4  0.7 2.9  2.9  0.4   17.3
 2006 0.8  2.7  0.3  1.4  6.2 -2.6  2.1 2.8  0.5 0.3  0.7  3.1   19.6
 2007 1.3  0.1  1.4  0.1  1.6 -1.0  1.0 1.5 -0.7 1.0  1.3 -0.7    7.0
 2008 1.4 -1.2  2.2  1.2 -0.3 -0.8  2.2 0.4  1.1 0.1  4.4 -1.3    9.7
 2009 4.8  3.2  1.6  3.5  0.7  1.7  2.1 2.2  2.5 1.9  1.5  2.8   32.4
 2010 3.5  0.5  0.4  1.3  1.8  3.8  3.7 3.0  1.1 1.2  3.9  3.4   31.2    
 2011 4.3  2.1  1.6 -0.8  3.9  1.5  4.0 5.4  2.3 2.9  0.2  1.5   33.0
 2012 1.1  1.9 -0.1  2.3  1.0  3.6  1.5 0.7  0.0 1.5  1.2  0.5   16.3
 2013 0.8  2.5  1.2  1.4  0.0  1.7  2.3 1.7  0.5 0.2  1.3  0.6   15.1
 2014 0.1  0.7  0.3 -0.7  1.0  1.0  0.2 0.9 -0.7 2.3  1.4  1.4    8.2
 2015 2.3  1.0  1.1  3.1  4.5 -0.7 -0.3 2.3  2.4 0.4 -1.3  1.0   16.7
 2016 2.1  2.5  0.9  1.0  0.2   NA   NA  NA   NA  NA   NA   NA    7.0

I would like to create a plot with something like this for the colors of the numbers: ifelse(values< 0,'red','black').

I tried with the addtable2plot function, from the plotrix package with bad results. Any tips about this problem? Thank you in advance guys.

EDIT: I need something like this but with the negative numbers in red:

textplot(Hmisc::format.df(tabRet, na.blank=TRUE, numeric.dollar=FALSE, cdec=rep(1,dim(tabRet)[2])), rmar = 0.8, cmar = 1, max.cex=.9, halign = "center", valign = "center", row.valign="center", wrap.rownames=20, wrap.colnames=10, col.colnames="Darkblue",col.rownames="Darkblue", mar = c(0,0,4,0)+0.1) title(main="Calendar Monthly Returns",col.main="Darkblue", cex.main=1)

PLOT


Solution

  • Simply add col.data=ifelse(tabRet<0,'red','black'), after col.rownames="Darkblue", to your code