tmhs
tmhs

Reputation: 1070

how to visualise data to compare with multiple conditions? ggplot2, r, geom_bar()

This is the sample data (Any tips on how to create the sample data more efficiently?)

# sample data

    city = c("paris", "tokyo", "seoul", "shanghai", "rome", "berlin",
             "paris", "tokyo", "seoul", "shanghai", "rome", "berlin",
             "paris", "tokyo", "seoul", "shanghai", "rome", "berlin",
             "paris", "tokyo", "seoul", "shanghai", "rome", "berlin")
    week = c(41,41,41,41,41,41,
             42,42,42,42,42,42,
             41,41,41,41,41,41,
             42,42,42,42,42,42)
    type = c("A","A","A","A","A","A",
             "B","B","B","B","B","B",
             "C","C","C","C","C","C",
             "A","B","C","A","B","C")
    count = sample(1:100, 24, replace = F)

df = data.frame(city,count,week,type)
df <- data.table(df)
df[, .(count=sum(count)), by =.(city,type, week)]

This is the graph I initially created.

# graph 1
ggplotly(
        ggplot(df, aes(reorder(city,-count), count)) + 
                geom_bar(stat="identity", aes(color=type, fill=type)) +
                scale_y_continuous(labels = comma) +
                theme(axis.text.x = element_text(angle= 90, hjust=1),
                      legend.position= "bottom")+
                guides(fill=FALSE)+
                coord_flip()+
                facet_grid(~week)
)

enter image description here

I basically want to compare the counts per city by week, and want to reshape it using "dodge" to compare.

enter image description here

^^^ Something like that would be great, but the bar should be "stack" type break down into types and then group by week.

Here is the graph I gave a try.

# graph2

position = position_dodge(width = .75)
width = .65
ggplotly(
        ggplot(df, aes(x = city, y = count, label = count, fill = type, group = week)) + 
                geom_bar(width = width, stat='identity', position = position) +
                geom_text(hjust = -0.5, size = 3, position = position) +
                coord_flip()
)

enter image description here

Now, this looks really ugly and not comprehensible at all.

My question is -> how to distinguish the week and then break them down into types while still labeling the counts so I can compare the weekly differences?

Upvotes: 1

Views: 665

Answers (1)

Romain
Romain

Reputation: 21948

Welcome to the Tidyverse!

I think you can use interaction to group week and city. The legend has to be reworked, but it seems to look like what you want to obtain.

library(tidyverse)

df <- tibble(week, city, type, count)

df %>% 
  group_by(city, week, type) %>%
  summarise(count = sum(count)) %>%
  ggplot() +
  geom_bar(aes(x = interaction(week, city), y = count, fill = type), 
           stat = "identity")

enter image description here

Upvotes: 1

Related Questions