簡體   English   中英

如何使用 R ggplot2 將堆疊直方圖創建為條形碼圖,其中包含來自 R 基表的行式顏色模式

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

這個問題最初發布在這里,但尚未找到解決方案。

在這里,我想問一下着色問題的任何解決方案,同時保持整體繪圖布局,可能使用 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)

layout_NO_color

這正是我需要的布局,但是我無法想出一種方法來為列中的不同行着色,它只能為行中的列着色。

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 解決方案來解決這個問題並獲得與上面完全相同的繪圖布局,但根據提供的顏色向量着色條形?

也許用ggplot2tidyverse函數試試這個方法:

library(tidyverse)
#Code
test.matrix %>% as.data.frame.matrix %>% rownames_to_column('Var') %>%
  pivot_longer(-Var) %>%
  mutate(name=factor(name,levels = rev(unique(name)),ordered = T)) %>%
  ggplot(aes(x=name,y=value,fill=Var))+
  geom_bar(stat='identity',color='black',position='fill')+
  coord_flip()+
  scale_fill_manual(values=c('BC.1'="gold",'BC.2'="yellowgreen",
                             'GC'="navy",'MO'="royalblue",'EB'="orangered"))+
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

輸出:

在此處輸入圖片說明

另一種選擇可以是:

#Code 2
test.matrix %>% as.data.frame.matrix %>% rownames_to_column('Var') %>%
  pivot_longer(-Var) %>%
  mutate(name=factor(name,levels = rev(unique(name)),ordered = T)) %>%
  ggplot(aes(x=name,y=value,fill=Var))+
  geom_bar(stat='identity',color='black')+
  coord_flip()+
  facet_wrap(name~.,scales = 'free',strip.position = 'left',ncol = 1)+
  scale_fill_manual(values=c('BC.1'="gold",'BC.2'="yellowgreen",
                             'GC'="navy",'MO'="royalblue",'EB'="orangered"))+
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank())

輸出:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM