Barplot with outline per unit?

Viewed 55

I want a barplot that outlines per unit in the y-axis. For example, the plot below using the iris dataset will plot a smooth barplot, however what I want is to outline each unit. I drew in the box to illustrate.

library(ggplot2) 
freqtable <- table(iris$Petal.Width)
df <- as.data.frame.table(freqtable)
colnames ( df ) = c( "Width", "Freq")
df$Width = as.numeric ( as.character ( df$Width ) )


ggplot(df[ df$Width > 2.2, ] , aes( Width , Freq)) +
  geom_bar(position="stack", stat="identity", fill="tomato2")

enter image description here

2 Answers

A bit of a hack but this does the job :

library(tidyverse)
df2 <- 
  uncount(df[ df$Width > 2.2, ] , Freq) %>%
  mutate(Freq=1)
  

ggplot(df2, aes( Width , Freq)) +
  geom_bar(position="stack", stat="identity", fill="tomato2", color = "black")

Created on 2021-09-12 by the reprex package (v2.0.1)

Now I have it. Different approach:

library(tidyverse)

df1 <- df[ df$Width > 2.2, ]

df1 %>% 
    group_by(Freq) %>% 
    slice(rep(1:n(), each = Freq)) %>% 
    mutate(segm = Freq/Freq) %>% 
    ggplot(aes(Width, segm, fill= "red")) +
    geom_col(position = "stack", color="black")+
    scale_y_continuous(breaks = seq(0, 10, by = 1)) +
    labs(y = "Freq")+
    guides(fill="none")

enter image description here

Related