簡體   English   中英

嘗試從百分比繪制堆積條形圖

[英]Trying to plot stacked barplot from percentages

我正在嘗試繪制不同部門使用的計算機速率的堆積條形圖,並詳細說明每個欄中的PC類型(以便每個部門type1 + type2 + type3 = tot_rate)。 我有一個看起來像這樣的數據框:

dat=read.table(text = "Tot_rate   Type1   Type2   Type3
DPT1 72 50 12 10 
DPT2 80 30 20 30
DPT3 92 54 14 24", header = TRUE)

我試圖用原始數據繪制我的地圖,但現在非常重要的一點是我要用百分比來繪制地圖,而我似乎不明白我該怎么做。

這就是我以為我可以做到的方式,但是那是行不通的

p<-ggplot(dat, aes(x=row.names(dat), y=dat$Tot_rate, fill=data[,2:ncol(dat)])) + geom_bar(stat="identity")+theme_minimal()+xlab("") + ylab("PC rate")+geom_abline(slope=0, intercept=90,  col = "red",lty=2) + theme(axis.text.x = element_text(angle = 90, hjust = 1))
p

當我嘗試上面的代碼時,我得到:

Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (9): fill

你能幫忙嗎? 謝謝你,利亞納

這是使用稱為ggstatsplotggplot2擴展軟件包進行操作的一種方法-

set.seed(123)
library(tidyverse)

# creating dataframe in long format
(dat <- read.table(
  text = "Tot_rate   Type1   Type2   Type3
DPT1 72 50 12 10 
DPT2 80 30 20 30
DPT3 92 54 14 24",
  header = TRUE
) %>%
  tibble::rownames_to_column(var = "id") %>%
  tidyr::gather(., "key", "counts", Type1:Type3))

#>     id Tot_rate   key counts
#> 1 DPT1       72 Type1     50
#> 2 DPT2       80 Type1     30
#> 3 DPT3       92 Type1     54
#> 4 DPT1       72 Type2     12
#> 5 DPT2       80 Type2     20
#> 6 DPT3       92 Type2     14
#> 7 DPT1       72 Type3     10
#> 8 DPT2       80 Type3     30
#> 9 DPT3       92 Type3     24

# bar plot
ggstatsplot::ggbarstats(dat,
                        main = id,
                        condition = key,
                        counts = counts,
                        messages = FALSE)

reprex軟件包 (v0.3.0)創建於2019-05-27

library(reshape2)

dat=read.table(text = "Department Tot_rate   Type1   Type2   Type3
DPT1 72 50 12 10 
DPT2 80 30 20 30
DPT3 92 54 14 24", header = TRUE)


long_dat <- dat[-2] %>% gather(type,number,Type1:Type3,-c("Department"))

首先,我重塑了您擁有的數據:將部門放在一列中,並將您的數據從寬格式重整為長格式(刪除了tot_rate,此處不需要)。

p <- ggplot(data=long_dat,aes(x=Department,y=number,fill=type)) +
  geom_bar(position = "fill",stat = "identity")

p

要按比例縮放條形圖,我們使用geom_barposition參數設置為position=fill

暫無
暫無

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

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