繁体   English   中英

在多级ggplot2图中用标签替换图例

[英]Replacing legend with labels in multilevel ggplot2 plot

我创建了这张图表。 标签占用太多空间,很难看到哪个状态。 因此,我想用图形或波纹管x轴内的州代码标签代替图例。 是否有捷径可寻?

图表: 在此处输入图片说明

生成它的代码:

url <- 'https://www.dropbox.com/s/f046jroutvt8ctk/SO_example_data_put_labels_in_graph.csv?raw=1'
d <- read_csv(url)

d %>% 
  ggplot(aes(x=popNb,y=tx_atendimento)) +
  geom_rect(aes(xmin=pop1b,xmax=popNb,
                ymin=tx0,ymax=tx_atendimento,
                fill=UF)) +
  geom_segment(aes(x=pop1b,xend=popNb,
                   y=tx_atendimento_UF,yend=tx_atendimento_UF)) +
  theme(legend.position = "bottom", legend.direction = "horizontal" ) +
  ggtitle('Daycare provision rate per state and municipality in Brazil (2014)') +
  ggsave('plot_rec_bar_needs_labels.png')

说明:

请注意,这不是正常的条形图。 每个自治市(数据集中的行)均由一个矩形表示,其宽度对应于该年龄段的儿童人数,高度对应于供应率。 我创建了x值,因此首先按州(UF)的平均供给率来安排市,然后按州的市(cod_mun6)中的相同率来安排市。 我还添加了显示每个城市平均值的条形图,尽管这些数据仅在每个城市的首次观察中可用。

因此,此图将市政和州级别的信息混合在一起(尽管它们只是在一个data.frame中被“非规范化”了)。

我知道可以通过以下方式删除图例: + theme(legend.position = "none", )我尝试使用以下方式添加标签:

  • + geom_label(aes(x=mean_popNb_uf,label=UF2), nudge_y =.4,label.size = 0.05 )
  • + geom_text(aes(label=UF2))

但是结果标签看起来很混乱,而且定位看起来很奇怪。

我还尝试了ggrepel软件包中的geom_text_repel(aes(label=UF2)) ,但未显示任何标签。 过去,我过去使用过包directlabels ,但在这种情况下不知道如何使用它。

最好的方法可能是将facet_wrap设置为1行以分离出状态。 请注意,似乎某些状态缺少数据,因此需要将其过滤掉(否则,当尝试为空图设置x轴限制时, facet_wrap失败:

d %>% 
  filter(!is.na(pop1b)
         , !is.na(popNb)) %>%
  ggplot(aes(x=popNb,y=tx_atendimento)) +
  geom_rect(aes(xmin=pop1b,xmax=popNb,
                ymin=tx0,ymax=tx_atendimento
                )) +
  geom_segment(aes(x=pop1b,xend=popNb,
                   y=tx_atendimento_UF,yend=tx_atendimento_UF)) +
  theme(axis.text.x = element_blank()) +
  ggtitle('Daycare provision rate per state and municipality in Brazil (2014)') +
  facet_wrap(~UF, scales = "free_x", nrow = 1, switch = "x") +
  theme_minimal()

请注意,如果要更改排序,则需要将UF列的因子级别设置为所需的任何顺序。

剧情

如果需要显示状态的“大小”,可以使用facet_grid其中space = "free"例如

d %>% 
  filter(!is.na(pop1b)
         , !is.na(popNb)) %>%
  ggplot(aes(x=popNb,y=tx_atendimento)) +
  geom_rect(aes(xmin=pop1b,xmax=popNb,
                ymin=tx0,ymax=tx_atendimento
                )) +
  geom_segment(aes(x=pop1b,xend=popNb,
                   y=tx_atendimento_UF,yend=tx_atendimento_UF)) +
  ggtitle('Daycare provision rate per state and municipality in Brazil (2014)') +
  # facet_wrap(~UF, scales = "free_x", nrow = 1, switch = "x") +
  facet_grid(~UF, scales = "free_x", switch = "x", space = "free") +
  theme_minimal() +
  theme(axis.text.x = element_blank()
        , panel.margin.x = unit(0,"in"))

但是请注意,如果某些状态太窄而无法容纳标签,则可能需要填充一些状态。

在此处输入图片说明

我继续并添加了代码以将所有状态填充到任意所需的宽度并对值进行排序:

library(dplyr)
library(ggplot2)
library(magrittr)
url <- 'https://www.dropbox.com/s/f046jroutvt8ctk/SO_example_data_put_labels_in_graph.csv?raw=1'
# d <- read.csv(url)

desiredWidth <- 350000

toPlot <-
  d %>%
  filter(!is.na(pop1b)
         , !is.na(popNb)
         , !is.na(UF)) %>%
  split(.$UF) %>%
  lapply(function(thisState){
    # thisState <- d %>% filter(UF == "AC")
    # Find current range:
    currRange <-
      thisState %>%
      {max(.$popNb, na.rm = TRUE) -
          min(.$pop1b, na.rm = TRUE)}

    spacing <- (desiredWidth - currRange)/2

    # Add the spacing
    temp <- thisState[1:2,]
    temp$pop1b <-
      c(min(thisState$pop1b, na.rm = TRUE) - spacing
        , max(thisState$popNb, na.rm = TRUE) + 1
        )
    temp$popNb <-
      c(min(thisState$pop1b, na.rm = TRUE) - 1
        , max(thisState$popNb, na.rm = TRUE) + spacing
      )
    temp$tx_atendimento <- 0
    return(rbind(thisState , temp))
  }) %>%
  bind_rows %>%
  filter(!is.na(UF)) %>%
  droplevels

# summary values
sumVal <-
  toPlot %>%
  group_by(UF) %>%
  summarise(sumVal = tx_atendimento_UF[1])

# Sort the states:
toPlot$UF <-
  factor(
    toPlot$UF
    , levels = as.character(sumVal$UF)[order(sumVal$sumVal)]
  )


toPlot %>% 
  ggplot(aes(x=popNb,y=tx_atendimento)) +
  geom_rect(aes(xmin=pop1b,xmax=popNb,
                ymin=tx0,ymax=tx_atendimento
                )) +
  geom_segment(aes(x=pop1b,xend=popNb,
                   y=tx_atendimento_UF,yend=tx_atendimento_UF)) +
  ggtitle('Daycare provision rate per state and municipality in Brazil (2014)') +
  # facet_wrap(~UF, scales = "free_x", nrow = 1, switch = "x") +
  facet_grid(~UF, scales = "free_x", switch = "x", space = "free") +
  theme_minimal() +
  theme(axis.text.x = element_blank()
        , panel.margin.x = unit(0,"in"))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM