首页 > 解决方案 > 订购 geom_bar 组

问题描述

我有这个数据:

country                name                  value
   <chr>                  <chr>                 <dbl>
 1 Germany                Jd                    7.1
 2 Germany                Jc                    8.4
 3 Germany                Ne                    1.3
 4 France                 Jd                    8.3
 5 France                 Jc                    12  
 6 France                 Ne                    3.7

我想将它绘制成两组条形图(每组三列)。与数据框中的顺序相同:第一个德国,第二个法国以及 Jd、Jc、Ne 列的顺序。

我做了:

p <- ggplot(data, aes(x = country, y = value)) +
    geom_bar(aes(fill = name), width=0.7, position = position_dodge(width=0.7), stat='identity')

但我以不同的顺序得到情节:首先是法国,然后是德国,以及列 Jc、Jd、Ne 的顺序。(似乎按字母顺序排列)。

我怎样才能以我想要的方式订购酒吧?

标签: rggplot2geom-bar

解决方案


控制排序的最简单方法之一可能是转换as.factor()您的排序列并定义级别,您将覆盖任何其他默认排序:

library(ggplot2)
data$country <- factor( data$country, levels = c("Germany", "France"))
data$name    <- factor( data$name, levels = c("Jd", "Jc", "Ne"))


ggplot(data, aes(x = country, y = value,fill = name)) +
# moved the aes() all together, nothing related to the question
geom_bar(width=0.7, position position_dodge(width=0.7), stat='identity')

在此处输入图像描述


data

data <- read.table(text = "
country                name                  value
  Germany                Jd                    7.1
  Germany                Jc                    8.4
  Germany                Ne                    1.3
  France                 Jd                    8.3
  France                 Jc                    12  
  France                 Ne                    3.7",header = T)

推荐阅读