Reputation: 2561
I have a table with 2 columns. First column is a test name and second column is success/failure of the test. I want to plot this in such a way that the plot area is split into grids of squares/rectangles and each test name belongs to one square/rectangle. The background color should be green if the test is a success and red otherwise. Basically a treemap but with all the rectangles of same size.
ret = data.frame("x" = c("test1","test2","test3","test4"), "y" = c("success","success","failure","success"))
I want this to be plotted such that 4 cells are formed with the test name displayed in the center. The background color for test3 block should be red and green for the rest. I tried using treemap package and portfolio package's map.market function but both of them are treemap functions and even after giving the size parameter same for all, they still give me different sizes for each cell.
Any help would be greatly appreciated.
Upvotes: 2
Views: 4416
Reputation: 18759
A fairly simple base
graphics solution, using function image
:
tableplot <- function(ret, nrow, ncol, main){
m <- matrix(as.integer(ret$y),nrow,ncol)
image(1:nrow,1:ncol,m,col=c("red","green"),axes=FALSE, xlab="",ylab="",main=main)
text(row(m),col(m),labels=matrix(ret$x,nrow,ncol))
}
Example:
ret <- data.frame("x" = c("test1","test2","test3","test4"), "y" = c("success","success","failure","success"))
tableplot(ret, 2, 2, "My tests")
Upvotes: 2
Reputation: 2051
It can also be done with the treemap package:
ret$index <- factor(ret$x)
ret$area <- 1
ret$color <- factor((ret$x=="test3") + 1, labels=c("Green", "Red"))
tmPlot(ret, index="ind",
vSize="value2",
vColor="isgreen",
type="categorical",
palette=c("darkolivegreen1", "darksalmon"),
position.legend="none",
fontsize.labels=14,
title="My test with the treemap package")
But once you have a working solution with ggplot2 (like the answer above), that one is hard to beat for further tweaking and customization.
Upvotes: 2
Reputation: 118889
I'd get the data in this format:
# > ret
# x y xmin xmax ymin ymax
# 1 test1 success 0 3 0 1
# 2 test2 success 0 3 1 2
# 3 test3 failure 3 6 0 1
# 4 test4 success 3 6 1 2
Then do this:
ggplot(ret, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)) +
geom_rect(colour="white", alpha = 0.5, aes(fill=y)) +
scale_fill_manual(values=c("red", "green"), guide=FALSE) +
geom_text(aes(x=(xmin+xmax)/2, y=(ymin+ymax)/2, label=x)) +
theme_bw() + theme(axis.text.y = element_blank(),
axis.text.x = element_blank(), axis.ticks.x = element_blank(),
axis.ticks.y = element_blank(), panel.grid.major.x = element_blank(),
panel.grid.major.y = element_blank(), panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank()) + xlab("") + ylab("") +
ggtitle("My tests")
This is what I get:
I'll leave any further minor tweaks you may seek to you.
Upvotes: 3