我要做一个柱状图,其中最大的柱状图离y轴最近,最短的柱状图离y轴最远。这有点像我的表格

    Name   Position
1   James  Goalkeeper
2   Frank  Goalkeeper
3   Jean   Defense
4   Steve  Defense
5   John   Defense
6   Tim    Striker

所以我试图建立一个条形图,根据位置显示球员的数量

p <- ggplot(theTable, aes(x = Position)) + geom_bar(binwidth = 1)

但是图表显示的是门将栏,然后是防守栏,最后是前锋栏。我希望图表的顺序是,防守条最靠近y轴,守门员条,最后是前锋条。 谢谢


当前回答

@GavinSimpson:重新排序是一个强大而有效的解决方案:

ggplot(theTable,
       aes(x=reorder(Position,Position,
                     function(x)-length(x)))) +
       geom_bar()

其他回答

@GavinSimpson:重新排序是一个强大而有效的解决方案:

ggplot(theTable,
       aes(x=reorder(Position,Position,
                     function(x)-length(x)))) +
       geom_bar()

你可以简单地使用下面的代码:

ggplot(yourdatasetname, aes(Position, fill = Name)) + 
     geom_bar(col = "black", size = 2)

如果图表列来自一个数值变量,如下面的数据框架所示,您可以使用一个更简单的解决方案:

ggplot(df, aes(x = reorder(Colors, -Qty, sum), y = Qty)) 
+ geom_bar(stat = "identity")  

排序变量(-Qty)前面的负号控制排序方向(升序/降序)

以下是一些用于测试的数据:

df <- data.frame(Colors = c("Green","Yellow","Blue","Red","Yellow","Blue"),  
                 Qty = c(7,4,5,1,3,6)
                )

**Sample data:**
  Colors Qty
1  Green   7
2 Yellow   4
3   Blue   5
4    Red   1
5 Yellow   3
6   Blue   6

当我发现这条线索时,这就是我一直在寻找的答案。希望对其他人有用。

如果不想使用ggplot2,还有一个ggpubr,它为ggbarplot函数提供了一个非常有用的参数。你可以对条形图进行排序。Val在“desc”和“asc”中是这样的:

library(dplyr)
library(ggpubr)
# desc
df %>%
  count(Position) %>%
  ggbarplot(x = "Position", 
            y = "n",
            sort.val = "desc")

# asc
df %>%
  count(Position) %>%
  ggbarplot(x = "Position", 
            y = "n",
            sort.val = "asc")

由reprex包于2022-08-14创建(v2.0.1)

如您所见,对条形进行排序非常简单。如果条形图是分组的,也可以这样做。查看上面的链接,获取一些有用的例子。

使用scale_x_discrete (limits =…)指定条形图的顺序。

positions <- c("Goalkeeper", "Defense", "Striker")
p <- ggplot(theTable, aes(x = Position)) + scale_x_discrete(limits = positions)