在ggplot条形图中为多个条形添加组标签

时间:2018-06-06 20:15:24

标签: r ggplot2

我有数据框

DF <- data.frame(V1 = factor(c("Option 1", "Option 1", "Option 1", "Option 2", "Option 1", "Option 2", "Option 1", "Option 1", "Option 2", NA, "Option 2", "Option 1", "Option 2", "Option 1", "Option 2", "Option 1", "Option 2", "Option 1")),
                  Location = factor(c("California", "Georgia", "Texas", "Texas", "Georgia", "Georgia", "California", "Georgia", "Texas", "Texas", "California", "Georgia", "Mexico", "Mexico", "Mexico", "Canada", "Canada", "Canada")))

当我在ggplot中绘制它时,由于美国各州和其他两个国家并排显示,它会有点混乱:

DF %>%
  filter(!is.na(V1)) %>% 
  ggplot(aes(Location, ..count..)) +
  geom_bar(aes(fill = V1), position = "dodge")

我可以通过重新排序Location变量的级别来使图更清晰:

DF$Location = factor(DF$Location, levels=c("Canada", "Mexico", "California", "Georgia", "Texas"))
DF %>%
  filter(!is.na(V1)) %>% 
  ggplot(aes(Location, ..count..)) +
  geom_bar(aes(fill = V1), position = "dodge")

但是,我想以某种方式标记加利福尼亚州,佐治亚州和德克萨斯州是美国的州,例如(但不一定)通过在这三个州的名称下添加“美国”。有没有办法做到这一点?

以下评论者表示这是重复的。我不这么认为。在与下面相关的案例中,数据框中已经存在“国家” - 等价类别。我当然可以创建一个,但对于大型数据帧来说却很耗时。我希望能够在剧情中添加“国家”标签。

1 个答案:

答案 0 :(得分:1)

我会使用facet_grid将美国各州和其他地点分成不同的面板。像这样:

DF$isUS <- ifelse(DF$Location %in% c("California", "Georgia", "Texas"), "US States", "Rest of world")

DF %>%
  filter(!is.na(V1)) %>% 
  ggplot(aes(Location, ..count..)) +
  geom_bar(aes(fill = V1), position = "dodge") +facet_grid(~isUS, space="free", scales="free")

enter image description here