ggplot2中的图例排序和因子排序

时间:2017-04-02 12:26:18

标签: r ggplot2 legend

我制作了以下代码:

#library(tidyverse)
#library(ggplot2)
#library(forcats)


    temp<-tribble(
 ~kt, ~yes, ~'no', ~'NA',
 "Berne", 47,33, 0,
 "Basel", 60,45,0,
 "Geneva", 64,61,0,
 "Zurich", 19,107,3
)

temp2 <- gather(temp, ' ', val, -kt)
ggplot(temp2, aes(kt, val, fill = ` `)) + 
  geom_col(position = 'fill', color='darkgrey') +
  geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3) +
  scale_y_continuous(labels = scales::percent_format())+
  theme_bw()+
  labs(x='Jurisdiction', y='Percentage') +
  coord_flip()+ scale_fill_grey(start = 0.9, end = .5) +
  guides(fill=guide_legend(title="Witnesses heard"))

现在我遇到了以下困难,如果有人能帮助我,我将不胜感激:

  • 如何更改图例的顺序?顺序应该反转(但是条形图的排序很好)。

  • 显然,y轴(管辖区)似乎按字母顺序排序,但我宁愿手动订购(如同在tibble中)。不幸的是,我没有设法解决这个问题。

感谢您的任何建议!

2 个答案:

答案 0 :(得分:1)

回答你的两个问题:

  1. 将参数reverse = T添加到您的最后一行,将其更改为:guides(fill = guide_legend(title = "Witnesses heard", reverse = T))
  2. 由于您已经建议forcats,因此您可以使用fct_releveltemp2 <- temp2 %>% mutate(kt = fct_relevel(kt, "Berne"))。只需指定"Berne"即可将其移至前面。您也可以指定所有级别,例如fct_relevel(kt, "Berne", "Basel", "Geneva", "Zurich"),但这不是必需的。
  3. 完整示例

    temp2 <- gather(temp, ' ', val, -kt) %>% 
      mutate(kt = fct_relevel(kt, "Berne"))
    
    # the following is just for convenience when plotting twice
    layers <- list(
      geom_col(position = 'fill', color='darkgrey'),
      geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3),
      scale_y_continuous(labels = scales::percent_format()),
      theme_bw(),
      labs(x='Jurisdiction', y='Percentage'),
      coord_flip(),
      scale_fill_grey(start = 0.9, end = .5),
      guides(fill = guide_legend(title = "Witnesses heard", reverse = T))
    )
    
    ggplot(temp2, aes(kt, val, fill = ` `)) +
      layers
    

    此外,您可以使用fct_rev来反转y轴上的位置:

    ggplot(temp2, aes(fct_rev(kt), val, fill = ` `)) +
      layers
    

答案 1 :(得分:0)

temp2 <- gather(temp, ' ', val, -kt)
temp2[,2] <- as.factor(temp2[[2]])
temp2[,2] <- factor(temp2$` `, levels = rev(levels(temp2$` `)))

temp2[,1] <- as.factor(temp2[[1]])
temp2[,1] <- factor(temp2$kt, levels = rev(levels(temp2$kt)))

ggplot(temp2, aes(kt, val, fill = ` `)) + 
  geom_col(position = 'fill', color='darkgrey') +
  geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3) +
  scale_y_continuous(labels = scales::percent_format())+theme_bw()+
  labs(x='Jurisdiction', y='Percentage')+coord_flip()+ scale_fill_grey(start = 0.9, end = .5)+
  guides(fill=guide_legend(title="Witnesses heard"))