在ggplot2条形图中订购多个geom_bar

时间:2016-05-30 13:35:26

标签: r plot ggplot2 geom-bar

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

这是我做的:

  1. 根据每个国家的动物数量订购数据表

     plot <- within(plot, country <- factor(country, 
     levels=names(sort(table(country), decreasing=TRUE))))
    
  2. 绘制图表

    gg <- ggplot(data = plot, aes(x=country))
    
  3. 为狗添加栏

    dogs <- gg + 
    geom_bar(data = plot[plot$animal1 == 'dog',], #select dogs from animal1 variable
    stat="count")
    
  4. 如果我这样做,我会得到这个(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 个答案:

答案 0 :(得分: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列的新数据框:

  • 国家
  • 变量:&#34; dog&#34;或&#34; cat&#34;
  • 值:狗/猫的数量(每个国家)

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

答案 1 :(得分: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