在R中分组Barplot

时间:2015-05-15 22:31:04

标签: r

我们说我们有以下内容:

planet <- c("Earth", "Mars", "Jupiter", "Venus")
trips <- 1:20
pilot <- 1:4

data <- data.frame(Planet = sample(planet, 20, replace=T), 
                   Pilot = sample(pilot, 20, replace=T),
                   Trips = sample(trips, 20, replace=T))

如何创建条形图,其中Y轴是行程数,X轴是引导数,但是对于每个X值/间隔,我们没有一个条而是四个(每个行星一个) ?

1 个答案:

答案 0 :(得分:2)

ggplot中,这被称为&#34;被躲避&#34;棒图:

library(ggplot2)
ggplot(data, aes(x = as.factor(Pilot), y = Trips, fill = Planet)) +
    geom_bar(stat = "identity", position = "dodge")

另一个选项,有方面:

ggplot(data, aes(x = Planet, y = Trips)) +
    geom_bar(stat = "identity", position = "dodge", fill = "dodgerblue") +
    facet_wrap(~ Pilot)