在ggplot图例中手动放置标签

时间:2018-12-05 11:16:31

标签: r ggplot2

我想知道是否可以在ggplot中的图例中手动放置标签?

我的示例是这样的:我有一个国家/地区的数据,并且每个洲都在做100%堆积的条形,所以我有:

dt <- data.table(continent = c(rep('Africa', 2), rep('Asia', 3), rep('Europe', 4)),
                 country = c('Nigeria', 'Kenya',
                             'China', 'India', 'Japan',
                             'Germany', 'Sweden', 'Spain', 'Croatia'),
                 value = runif(9, 0, 10),
                 number=(1:9))


ggplot(data=dt, 
       aes(x = continent, y = value, fill = as.factor(number))) +
  geom_bar(stat = "identity", position = "fill", color='white', width=0.3 ) + 
  labs(x = '', y = 'Percentage') +
  scale_y_continuous(expand=c(0,0)) +
  scale_fill_manual('Country',
                    labels = dt[, country],
                    values = (grDevices::colorRampPalette(c('#BB16A3', '#f8e7f5')))(9)) +
  theme(legend.position='bottom', aspect.ratio = 1) +
  guides(fill = guide_legend(title.position="top", title.hjust = 0.5, reverse=T)) +
  coord_flip()

And the graph that I get is this

所以我的问题是,是否可以在图例中重新放置标签,以便每个大洲的国家/地区都位于单独的列中?还是另外一行?

谢谢!

1 个答案:

答案 0 :(得分:1)

我注意到每个大陆的国家/地区数量不同。 ggplot()可以按行或按列填充图例矩阵,但我从未见过在每个行/列中具有不同单元格数量的锯齿状矩阵。

但是,可以破解看起来像锯齿状图例矩阵的东西。这里是一些实现。如果要按特定顺序对洲/国家/地区标签进行排序,或者要更改图例键之间的间距等,则可能需要调整参数。

预备工作

# define fill mapping so that it can be re-used for both top plot & legend
scale_fill_country <- 
  scale_fill_manual(labels = dt[, country],
                    values = (grDevices::colorRampPalette(c('#BB16A3', '#f8e7f5')))(9))

# create top plot (without any legend)
gg.plot <- ggplot(data = dt, 
                  aes(x = continent, y = value, fill = as.factor(number))) +
  #note: geom_col is equivalent to geom_bar(stat = "identity")
  geom_col(position = "fill", color='white', width=0.3 ) + 
  labs(x = '', y = 'Percentage') +
  scale_y_continuous(expand=c(0,0)) +
  scale_fill_country +
  theme_classic() +
  theme(legend.position = "none") +
  coord_flip()

修改图例的数据源

library(dplyr)
dt.legend <- dt %>% 

  # pad with empty rows so that there are equal number of countries under
  # each continent
  group_by(continent) %>% 
  arrange(country) %>% 
  mutate(country.id = seq(1, n())) %>% 
  ungroup() %>% 
  tidyr::complete(continent, country.id, fill = list(country = " ")) %>%

  # make each empty row distinct (within the same continent), & sort them
  # after the original rows
  rowwise() %>%
  mutate(country = ifelse(country == " ", 
                          paste0(rep.int(" ", country.id), collapse = ""),
                          country)) %>%
  ungroup() %>%
  mutate(country = forcats::fct_reorder(country, country.id))

> dt.legend
# A tibble: 12 x 5
   continent country.id country   value number
   <chr>          <int> <fct>     <dbl>  <int>
 1 Africa             1 Kenya    2.02        2
 2 Africa             2 Nigeria  7.17        1
 3 Africa             3 "   "   NA          NA
 4 Africa             4 "    "  NA          NA
 5 Asia               1 China    3.21        3
 6 Asia               2 India    5.59        4
 7 Asia               3 Japan    9.31        5
 8 Asia               4 "    "  NA          NA
 9 Europe             1 Croatia  0.0131      9
10 Europe             2 Germany  0.0775      6
11 Europe             3 Spain    3.98        8
12 Europe             4 Sweden   0.703       7

版本1 :每个大陆在一个 中,标签 下方 键(如果您不希望显示与每一行关联的大洲标签,请将axis.text.y = element_blank()添加到theme()

gg.legend.rows1 <- ggplot(data = dt.legend,
                         aes(x = country, y = continent,
                             fill = as.factor(number))) +
  geom_tile(color = "white", size = 2) +
  facet_wrap(~ continent, scales = "free", ncol = 1) +
  scale_y_discrete(expand = c(0, 0)) +
  scale_fill_country +
  theme_minimal() +
  theme(axis.title = element_blank(),
        strip.text = element_blank(),
        panel.grid = element_blank(),
        legend.position = "none")

cowplot::plot_grid(gg.plot, gg.legend.rows1,
                   ncol = 1,
                   rel_heights = c(1, 0.3))

v1

第2版:每个大陆在一个 中,标签为 right 图例密钥(我想不出这种方法也可以获取大洲标签,但是我认为无论如何我都不认为这是必需的...)

gg.legend.rows2 <- ggplot(data = dt.legend,
       aes(x = "", y = country, fill = as.factor(number))) +
  geom_tile() +
  scale_y_discrete(position = "right", expand = c(0, 0)) +
  facet_wrap(~ interaction(continent, country, lex.order = TRUE), 
             scales = "free") +
  scale_fill_country +
  theme_minimal() +
  theme(axis.title = element_blank(),
        axis.text.x = element_blank(),
        strip.text = element_blank(),
        panel.grid = element_blank(),
        panel.spacing = unit(0, "pt"),
        legend.position = "none")

cowplot::plot_grid(gg.plot, gg.legend.rows2,
                   axis = "l", align = "v",
                   ncol = 1,
                   rel_heights = c(1, 0.2))

v2

版本3 :每个大洲都位于一个 中,并标记为 right 图例键(如果您不希望显示与各列关联的大洲标签,则将axis.text.x = element_blank()添加到theme()

gg.legend.columns <- ggplot(data = dt.legend,
                            aes(x = continent, y = forcats::fct_rev(country), 
                                fill = as.factor(number))) +
  geom_tile(color = "white", size = 2) +
  facet_wrap(~ continent, scales = "free", nrow = 1) +
  scale_x_discrete(position = "top", expand = c(0, 0)) +
  scale_y_discrete(position = "right", expand = c(0, 0)) +
  scale_fill_country +
  theme_minimal() +
  theme(axis.title = element_blank(),
        strip.text = element_blank(),
        panel.grid = element_blank(),
        legend.position = "none")

cowplot::plot_grid(gg.plot, gg.legend.columns, 
                   axis = "l", align = "v",
                   ncol = 1, 
                   rel_heights = c(1, 0.3))

v3