Search code examples
rggplot2bar-chartcategorical-data

How to make a line and dot chart to represent frequencies of categorical variables?


I would like to make a chart like in this picture instead of a barplot to represent frequencies of several categorical variables. the graph I want to make

This is a snippet of my data for the variable of interest:

c("Mixed", "Mixed", "Administrative", "Administrative", "Biophysical", 
"Biophysical", "Administrative", "Administrative", "Administrative", 
"Administrative", "Administrative")

And I have produced the following code inspired by this post and despite I do not get any error message, there is no plot drawn. I restarted R several times but it does not seem to be an issue. Any help would be very much appreciated!

hnvf9 <- hnvdata %>%
  select(Boundary)%>%
  mutate(Boundary1 = as.factor(Boundary))%>%
  count(Boundary1)%>%
  mutate(pct=n/sum(n))%>%
  ggplot(aes(Boundary1, pct)) +
  geom_linerange(aes(x = Boundary1, ymin = 0, ymax = 100,color = "lightgray", lwd = 1)) +
  geom_point(colour="red", size = 3)

Solution

  • This is known as a lollipop chart. You can create one in ggplot as follows

    x <- c("Mixed", "Mixed", "Administrative", "Administrative", "Biophysical", 
      "Biophysical", "Administrative", "Administrative", "Administrative", 
      "Administrative", "Administrative")
    
    library(ggplot2)
    
    ggplot(as.data.frame(table(x)/length(x)), aes(Freq, x)) +
      geom_linerange(aes(xmin = 0, xmax = Freq)) +
      geom_point(color = "#2aadab", size = 5) +
      geom_vline(xintercept = 0, color = 'gray50') +
      scale_x_continuous('Percent', breaks = 0:4 * 0.25, limits = c(0, 1),
                         labels = ~100*.x) +
      labs(y = NULL) +
      theme_bw(base_size = 16) +
      theme(panel.grid.minor.x = element_blank(),
            panel.grid.major.y = element_blank())
    

    enter image description here