Home > Blockchain >  Ploting categorical variable to get numbers at the top of the bars in R
Ploting categorical variable to get numbers at the top of the bars in R

Time:03-10

Here is a small sample of my data just to demonstrate the the plot of interest

df<-read.table (text=" P    U   W
A   F   F
M   M   F
N   F   F
A   F   F
M   M   F
N   M   F
Q   M   F
Q   M   F
R   F   M
R   F   M
", header=TRUE)

I want to get the following plot in ggplot2

enter image description here

The plots and numbers at the top of the bars are incorrect. I just wanted to demonstrate the plot of interest. Please do not use loop if at all possible.

CodePudding user response:

Given the lack of detail and specificity in the question, it's not possible for me to be sure of what you're looking for. Perhaps it is something like this.

library(tidyverse)

df<-read.table (text=" P    U   W
A   F   F
M   M   F
N   F   F
A   F   F
M   M   F
N   M   F
Q   M   F
Q   M   F
R   F   M
R   F   M
", header=TRUE)

x <- df %>%
  mutate(across(c(U, W), ~paste0(cur_column(), .x))) %>%
  pivot_longer(names_to = "series",
               values_to = "group",
               cols = c(U, W)) %>%
  group_by(group, P) %>%
  summarise(n = n())
#> `summarise()` has grouped output by 'group'. You can override using the
#> `.groups` argument.

x %>%
  ggplot(aes(x = P, y = n, fill = P))  
  geom_col()  
  geom_text(aes(label = n),
            vjust = -0.1)  
  scale_y_continuous(expand = expansion(mult = c(0, 0.1)))  
  facet_wrap(~group)

Created on 2022-03-10 by the reprex package (v2.0.1)

  • Related