繁体   English   中英

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

[英]legend ordering and factor ordering in ggplot2

我产生了以下代码:

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

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

  • 如何更改图例的顺序? 顺序应该颠倒(但是barplot的顺序很好)。

  • 显然,y轴(管辖权)似乎是按字母顺序排序的,但我宁愿手动对其进行排序(如小标题中所示)。 不幸的是,我没有解决这个问题。

谢谢您的任何建议!

回答您的两个问题:

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

完整的例子

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

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

暂无
暂无

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

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