Home > Back-end >  How to graph categorical variable
How to graph categorical variable

Time:07-28

Example data:

tibble::tribble(
  ~Item, ~Description,
   123L, "something1",
   123L, "something1",
   123L, "something1",
   321L, "something2",
   321L, "something2",
   321L, "something2"
  )

I am trying to graph on x axis the unique descriptions, in this case a separate bar for something1 and something2

And on y axis the count of unique items, in this case bar for both of them should be at one as they each have one item.

CodePudding user response:

You can use the following code:

library(ggplot2)
library(tibble)
library(dplyr)
tibble::tribble(
  ~Item, ~Description,
  123L, "something1",
  123L, "something1",
  123L, "something1",
  321L, "something2",
  321L, "something2",
  321L, "something2"
) %>%
  group_by(Description) %>%
  mutate(count = n_distinct(Item)/length(Item)) %>%
  ggplot(aes(x = Description, y = count))  
  geom_bar(stat = "identity")

Created on 2022-07-28 by the reprex package (v2.0.1)

CodePudding user response:

library(ggplot2)

ggplot(df, aes(x = Description, fill = Description))  
  geom_bar()  
  theme_bw()  
  ggtitle("Here's a title")  
  guides(fill="none")

  • Related