0

here is my data frame:

> mode of transportation       distance<1km      distance2km-5km    distance>5km 
     Car,truck,van                 4                  45               53 
     Bus                           3                  13               24 
     Subway,elevated,rail          0                  34               67

I want have percentage stacked bar plots that y is mode of transportation and x is the frequency. In the each bar, by using different color to distinguish the different of distance.

Thank you!

SHIRLEEN
  • 89
  • 5

1 Answers1

1

Here is one potential solution:

library(tidyverse)
df <- tribble(~"mode of transportation",       ~"distance<1km",    ~"distance2km-5km",    ~"distance>5km", 
"Car,truck,van",                 4,                  45,               53, 
"Bus",                           3,                  13,               24, 
"Subway,elevated,rail",          0,                  34,               67)

df %>% 
  pivot_longer(cols = -c(`mode of transportation`),
                         values_to = "Frequency",
                         names_to = "Distance") %>%
  mutate(Distance = factor(Distance,
                           levels = c("distance<1km",
                                      "distance2km-5km",
                                      "distance>5km"))) %>% 
  ggplot(aes(fill = Distance, y = Frequency, x = `mode of transportation`)) +
  geom_col(position = "fill") +
  scale_y_continuous(labels = scales::percent) +
  coord_flip()

example_1.png

jared_mamrot
  • 22,354
  • 4
  • 21
  • 46