简体   繁体   中英

Trying to plot stacked barplot from percentages

I'm trying to plot a stacked barplot of the rate of computer used in different departments with details on what type of PC in each bar( so that for each department type1+type2+type3=tot_rate) . I've got a dataframe that looks like this :

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)

I tried to plot my barplot with raw data but now it's very important that i get the one with percentages and i can't seem to understand how i can do that.

This is how i thought i could that, but it just doesn't work

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

When i try the code above i get :

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

Can you please help ? Thank you, Liana

Here is one way to do it using a ggplot2 extension package called ggstatsplot -

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)

Created on 2019-05-27 by the reprex package (v0.3.0)

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"))

First I reshaped the data you had : I put the department in a column and reshaped your data from wide to long format (dropped tot_rate which isn't needed here).

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

p

To scale the barplot in percantages, we use the position argument of geom_bar set to position=fill .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM