How to use R base plot to create a stacked histogram as barcode plot with row-wise color pattern from a R base table

给你一囗甜甜゛ 提交于 2021-01-07 03:54:30

问题


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)

plot(table)

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)

plot(table), colored)

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)

plot(t(table), colored)

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!