问题
I came across a neat feature when plotting a table with base::plot()
> test.matrix<-matrix(c(70,120,65,140,13,68,46,294,52,410),ncol=2,byrow=TRUE)
> rownames(test.matrix)<-c("BC.1","BC.2","GC","MO","EB")
> colnames(test.matrix)<-c("12m","3m")
> test.matrix <- as.table(test.matrix)
> test.matrix
12m 3m
BC.1 70 120
BC.2 65 140
GC 13 68
MO 46 294
EB 52 410
> plot(test.matrix)
This plots sth like a barcode plot, with bar height reflecting row-wise difference and bar width reflecting table cell value across entire numeric table content. So far so good. Now I want to color the variable by rownames:
> color.ct <- c("gold","yellowgreen","navy","royalblue","orangered")
> names(x = color.ct) <- rownames(test.matrix)
> color.ct
BC.1 BC.2 GC MO EB
"gold" "yellowgreen" "navy" "royalblue" "orangered"
> plot(test.matrix, col= color.ct)
This is not the desired outcome, as the barcode should be colored by rows, not columns.
Interestingly if I do
plot(t(test.matrix), col= color.ct)
Then it gives a vertical barcode with coloration as intended, however now the individual bar height differences are lost and a total column-wise difference is expressed as bar-width.
Does anyone have an idea how to get exactly the first figure with the coloration pattern of the third figure?
I am aware of the versatility of the ggplot2 package, which can definitely provide a similar solution for my question, which might however require lots of additional code to get the stacked bars displayed as fractions rather than absolutes, or maybe I am missing something.
来源:https://stackoverflow.com/questions/64121862/how-to-use-r-base-plot-to-create-a-stacked-histogram-as-barcode-plot-with-row-wi