简体   繁体   English

根据 2 列中的值重新排序 ggplot 中的标签

[英]Reorder labels in ggplot based on values in 2 colums

I would like to build a bar plot in R in which the labels in x axis are ordered by the value in Count if Name == A .我想在 R 中构建一个条形 plot ,其中 x 轴上的标签按Count如果Name == A的值排序。 When I build it, it simply order the x axis "Tool 1, Tool 2, Tool 3".当我构建它时,它只是简单地订购 x 轴“工具 1,工具 2,工具 3”。 What I would like is to get ax axis order like "Tool 3, Tool 1, Tool 2" (ordering by values in Name == A ).我想要的是获得像“工具 3,工具 1,工具 2”这样的轴顺序(按Name == A中的值排序)。

Here is a tiny dataframe as example:这是一个微型 dataframe 示例:

df <- rbind(tibble(Name = c('A', 'B', 'C'), Count = c(6, 3, 1), Method = rep('Tool 1', 3)),
        tibble(Name = c('A', 'B', 'C'), Count = c(4, 2, 4), Method = rep('Tool 2', 3)),
        tibble(Name = c('A', 'B', 'C'), Count = c(7, 3, 0), Method = rep('Tool 3', 3))
        )
df

# A tibble: 9 x 3
  Name  Count Method
  <fct> <dbl> <chr> 
1 A         6 Tool 1
2 B         3 Tool 1
3 C         1 Tool 1
4 A         4 Tool 2
5 B         2 Tool 2
6 C         4 Tool 2
7 A         7 Tool 3
8 B         3 Tool 3
9 C         0 Tool 3

To build the plot:要构建 plot:

p <- ggplot(df, aes(x = Method,
                       y = Count,
                       fill = Name)) +
  geom_bar(stat="identity")

p

在此处输入图像描述

I tried to rearrange it with df %>% mutate(Method = fct_reorder(Method, desc(Count))) but I don't know how to select only by A values.我试图用df %>% mutate(Method = fct_reorder(Method, desc(Count)))重新排列它,但我不知道如何仅通过 A 值来 select 。 I also could reorder it manually but I am interested in knowing how to do it automatically.我也可以手动重新排序,但我有兴趣知道如何自动进行。 Thanks for the help !谢谢您的帮助 !

We can add a column to df and use the reorder function我们可以向 df 添加一列并使用reorder function

df$Count_A <- ifelse(df$Name == "A", df$Count, NA)

ggplot(df, aes(x = reorder(Method, -Count_A, mean, na.rm = TRUE),
               y = Count,
               fill = Name))+
  geom_bar(stat="identity")

在此处输入图像描述

Alternatively, you could add the reorder ed factor to df :或者,您可以将reorder ed 因子添加到df

df$Method <- reorder(df$Method, -df$Count_A, mean, na.rm = TRUE)

ggplot(df, aes(x = Method, y = Count, fill = Name)) +
  geom_bar(stat="identity")

Using relevel .使用relevel

p <- ggplot(transform(df, Method=relevel(as.factor(Method), ref="Tool 3")), 
            aes(x = Method,y = Count, fill = Name)) +
  geom_bar(stat="identity")
p

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

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