我要做一个柱状图,其中最大的柱状图离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轴,守门员条,最后是前锋条。 谢谢


当前回答

如果不想使用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)

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

其他回答

如果不想使用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)

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

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

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

我认为已经提供的解决方案过于冗长。使用ggplot进行频率排序barplot的一种更简洁的方法是

ggplot(theTable, aes(x=reorder(Position, -table(Position)[Position]))) + geom_bar()

它类似于Alex Brown的建议,但更简短,并且不需要任何函数定义。

更新

我认为我的旧解决方案在当时是好的,但现在我宁愿使用forcats::fct_infreq,它是按频率排序因子级别:

require(forcats)

ggplot(theTable, aes(fct_infreq(Position))) + geom_bar()

另一种方法是使用重新排序来排列因子的级别。根据计数的升序(n)或降序(-n)。非常类似于使用forcats包中的fct_reorder:

降序排列

df %>%
  count(Position) %>%
  ggplot(aes(x = reorder(Position, -n), y = n)) +
  geom_bar(stat = 'identity') +
  xlab("Position")

升序排序 df % > % 数(位置)% > % ggplot(aes(x = reorder(Position, n), y = n)) + Geom_bar (stat = 'identity') + xlab(“位置”) 数据帧: df <- structure(list(Position = structure(c(3L, 3L, 1L, 1L, 1L, 2L), .Label = c("防御", "前锋","Zoalkeeper"), class = "factor"), Name =结构(c(2L, 1 l, 3 l 5 l 4 l, 6 l), .Label = c(“弗兰克”,“詹姆斯”,“琼”,“约翰”, "Steve", "Tim"), class = "factor")), class = "data.frame", row.names = c(NA, 6 l))

就像Alex Brown回答中的reorder()一样,我们也可以使用forcats::fct_reorder()。它基本上会对第一个参数中指定的因子进行排序,根据应用指定函数后第二个参数中的值(default = median,这是我们在这里使用的,因为每个因子级别只有一个值)。

遗憾的是,在OP的问题中,所需的顺序也是字母顺序,因为这是创建因子时的默认排序顺序,因此将隐藏此函数的实际操作。为了更清楚,我将“守门员”替换为“Zoalkeeper”。

library(tidyverse)
library(forcats)

theTable <- data.frame(
                Name = c('James', 'Frank', 'Jean', 'Steve', 'John', 'Tim'),
                Position = c('Zoalkeeper', 'Zoalkeeper', 'Defense',
                             'Defense', 'Defense', 'Striker'))

theTable %>%
    count(Position) %>%
    mutate(Position = fct_reorder(Position, n, .desc = TRUE)) %>%
    ggplot(aes(x = Position, y = n)) + geom_bar(stat = 'identity')