首页 文章

在ggplot2条形图中订购多个geom_bar

提问于
浏览
1

我正在制作一个条形图,显示各国不同的猫狗数量 . 猫和狗是存储在不同因子/变量中的水平 . 我想将每个动物计数的条形图绘制在另一个(即2层)之上,然后我想根据每个国家的动物频率从最高(即最高计数)到最低的顺序排序 .

这是我做的:

  • 根据每个国家/地区的动物数量排序数据表
plot <- within(plot, country <- factor(country, 
 levels=names(sort(table(country), decreasing=TRUE))))
  • 绘制图表
gg <- ggplot(data = plot, aes(x=country))
  • 为狗添加栏
dogs <- gg + 
geom_bar(data = plot[plot$animal1 == 'dog',], #select dogs from animal1 variable
stat="count")

如果我这样做,我得到这个(有一个 geom_bar ):

img

到现在为止还挺好 . 接下来,我为猫添加第二个geom_bar:

dogs_cats <- gg + 
geom_bar(data = plot[plot$animal1 == 'dog',], #select dogs from animal1 variable
stat="count") +
geom_bar(data = plot[plot$animal2 == 'cat',], #select cats from animal2 variable
stat="count")

现在订单已更改并且已关闭(在第二个 geom_bar 之后):

img

如何保持条形的顺序跟随最初的 geom_bar

非常感谢!

2 回答

  • 2

    我建议你使用 merge 来创建一个新的数据框:

    1.Sum up( ddplymelt

    require(plyr) #ddply
    require(reshape2) # melt
    
    df = ddply(plot, "country", summarize, dogs = sum(animal1 == "dog"), 
    cats = sum(animal2 == "cat"))
    dogs_and_cats = melt(df, id = "country")
    

    您可能有一个包含3列的新数据框:

    • 国家

    • 变量:"dog"或"cat"

    • 值:狗/猫的数量(每个国家)

    2.Plot

    ggplot(dogs_and_cats , aes(x = reorder(country, -value), y = value, fill = variable)) +
    geom_bar(stat = "identity", position = "dodge")
    

    3.Example:

    以下是 diamonds 数据集的示例,没有可重现的示例:

    df = ddply(diamonds, "cut", summarize, J = sum(color == "J"), 
    D = sum(color == "D"))
    plot = melt(df, id = "cut")
    
    ggplot(plot, aes(x = reorder(cut, -value), y = value, fill = variable)) +
    geom_bar(stat = "identity", position = "dodge")
    

    enter image description here

  • 0

    Hoom,我确实喜欢你的代码,但是酒吧的顺序并没有改变 . 也许你在某处犯了一个简单的错误 .

    library(ggplot2)
    # make a sample data
    set.seed(1); d <- data.frame(animal1 = sample(c("dog", "other"), replace=T, 10000, prob=c(0.7,0.3)), 
                                 animal2 = sample(c("cat", "other"), replace=T, 10000, prob=c(0.3,0.7)), 
                                 country = sample(LETTERS[1:15], replace=T, 10000, prob=runif(15,0,1)))
    levels(d$country)     # [1] "A" "B" "C" "D" ...
    plot <- within(d, country <- factor(country, levels=names(sort(table(country), decreasing=TRUE))))
    levels(plot$country)  # [1] "N" "O" "L" "F" ...
    
    gg <- ggplot(data = plot, aes(x=country))
    dogs <- gg + geom_bar(data = plot[plot$animal1 == "dog",], stat="count", fill="darkblue")
    dogs_cats <- gg + 
      geom_bar(data = plot[plot$animal1 == "dog",], stat="count", fill="darkblue") +
      geom_bar(data = plot[plot$animal2 == "cat",], stat="count", fill="blue")
    
    print(dogs)
    print(dogs_cats)     # I made below img using library(grid) to form two graphs.
    

    plot

相关问题