簡體   English   中英

R:帶有barpot,ggplot或plotly的堆積條形圖

[英]R: Stacked bar plot with barpot, ggplot or plotly

我一直在尋找解決方案,但是沒有一個已經存在的問題適合我的問題。

我有一個data.frame:

Pat <- c(1,1,1,1,1,1,2,2,2,2,2,2)
V_ID <- c(1,1,6,6,9,9,1,1,6,6,9,9)
T_ID <- c("A","B","A","B","A","B","A","B","A","B", "A","B")
apples <- c(1,1,1,1,1,1,1,1,1,1,1,1)
bananas <- c(2,2,2,2,2,2,2,2,2,2,2,2)
cranberries <- c(3,3,3,3,3,3,3,3,3,3,3,3)

df <- data.frame(Pat,V_ID, T_ID, apples, bananas, cranberries)

我正在嘗試繪制:

barplot(as.matrix(df[,4:6]) ,
    main="tobefound", horiz = FALSE,width = 1, 
    names.arg=colnames(df[,4:6]),
    las=2,
    col = c("blue", "red"),
    legend = df[,3],
    args.legend = list(x="topleft"),
    beside= FALSE)

BARPLOT

在此處輸入圖片說明

我需要進行兩項更改:首先,我希望將所有的“ B”(因此,每個堆棧中的紅色部分)堆積在一起,然后將藍色的頂部堆疊在一起。 第二:除了通過以下方式解決此問題外,是否還有一種方法可以將圖例僅減少到A和B

legend = df[1:2,3],

我也在尋找使用plotly或ggplot的解決方案。

謝謝,

第一次重塑:

df_long <- tidyr::gather(df, 'key', 'value', apples:cranberries) 

然后繪制:

ggplot(df_long, aes(key, value, fill = T_ID)) + geom_col(col = 'black')

在此處輸入圖片說明

也許沒有國界:

ggplot(df_long, aes(key, value, fill = T_ID)) + geom_col()

在此處輸入圖片說明

使用基本圖形,您需要首先按T_IDdf進行排序。

df = df[order(df$T_ID), ]

barplot(as.matrix(df[,4:6]) ,
        main="tobefound", horiz = FALSE,width = 1, 
        names.arg=colnames(df[,4:6]),
        las=2,
        ylim = c(0,40),
        col = 1+as.numeric(as.factor(df$T_ID)),
        border = NA,
        beside= FALSE)

box()
legend('topleft', fill = 1+as.numeric(as.factor(levels(df$T_ID))), legend = levels(as.factor(df$T_ID)))

在此處輸入圖片說明

暫無
暫無

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

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