如何可视化数据以与多个条件进行比较? ggplot2,r,geom_bar()

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

这是示例数据(关于如何更有效地创建示例数据的任何提示?)

# 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)]

这是我最初创建的图表。

# 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)
)

我基本上想按周比较每个城市的计数, 并想使用 "dodge" 重塑它以进行比较。

^^^ 有这样的东西就好了, 但栏应该是 "stack" 类型分解成类型,然后按周分组。

这是我试过的图表。

# 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()
)

现在,这看起来真的很难看,根本无法理解。

我的问题是 -> 如何区分周,然后将它们分解为类型,同时仍然标记计数,以便我可以比较每周的差异?

欢迎来到 Tidyverse!

我认为你可以使用 interaction 来分组 weekcity。传说要重做,不过好像是你想得到的样子

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")