如何使用 R ggplot2 创建堆叠直方图作为条形码图,并具有 R 基表中的按行颜色模式

这个问题最初在这里发布,但尚未找到解决方案。

在这里,我想询问任何解决着色问题的方法,同时保持整体绘图布局,可能使用 ggplot2 或其他方式。

简而言之,我想绘制类似于条形码图的内容,条形高度反映行列差异,条形宽度反映跨列的行总和。

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)

布局_NO_颜色

这正是我需要的布局,但是我无法找到一种方法来为跨列的不同行着色,它只为跨行的列着色。

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)

布局颜色

是否有任何 R 或 python 解决方案可以解决这个问题并获得与上面完全相同的绘图布局,但条形根据提供的颜色向量着色?


千巷猫影
浏览 60回答 1
1回答

郎朗坤

也许可以尝试使用以下方法ggplot2和tidyverse函数:library(tidyverse)#Codetest.matrix %>% as.data.frame.matrix %>% rownames_to_column('Var') %>%&nbsp; pivot_longer(-Var) %>%&nbsp; mutate(name=factor(name,levels = rev(unique(name)),ordered = T)) %>%&nbsp; ggplot(aes(x=name,y=value,fill=Var))+&nbsp; geom_bar(stat='identity',color='black',position='fill')+&nbsp; coord_flip()+&nbsp; scale_fill_manual(values=c('BC.1'="gold",'BC.2'="yellowgreen",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'GC'="navy",'MO'="royalblue",'EB'="orangered"))+&nbsp; theme(axis.text.x = element_blank(),&nbsp; &nbsp; &nbsp; &nbsp; axis.ticks.x = element_blank())输出:另一种选择可以是:#Code 2test.matrix %>% as.data.frame.matrix %>% rownames_to_column('Var') %>%&nbsp; pivot_longer(-Var) %>%&nbsp; mutate(name=factor(name,levels = rev(unique(name)),ordered = T)) %>%&nbsp; ggplot(aes(x=name,y=value,fill=Var))+&nbsp; geom_bar(stat='identity',color='black')+&nbsp; coord_flip()+&nbsp; facet_wrap(name~.,scales = 'free',strip.position = 'left',ncol = 1)+&nbsp; scale_fill_manual(values=c('BC.1'="gold",'BC.2'="yellowgreen",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'GC'="navy",'MO'="royalblue",'EB'="orangered"))+&nbsp; theme(axis.text.y = element_blank(),&nbsp; &nbsp; &nbsp; &nbsp; axis.ticks.y = element_blank())输出:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python