1

Let us say we have the following:

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))

How do I create a bar plot in which the Y axis is the number of trips, and the X axis is the pilot number, but for each X value/interval we have not one bar but four(one for each planet)?

isolier
  • 157
  • 5
  • 1
    `barplot(with(data, tapply(Trips, list(Planet, Pilot), sum)), beside = TRUE, legend.text = planet)` – rawr May 15 '15 at 22:43
  • Beautiful, this is exactly what I wanted; thank you. I selected the answer below because Gegor submitted it as an answer and it is also correct if one wants to use ggplot2. – isolier May 15 '15 at 23:00

1 Answers1

2

In ggplot, this is called a "dodged" bar-plot:

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

Another option, with facets:

ggplot(data, aes(x = Planet, y = Trips)) +
    geom_bar(stat = "identity", position = "dodge", fill = "dodgerblue") +
    facet_wrap(~ Pilot)
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • This produces exactly what I was looking for. For those interested, rawr's comment to my question answers this problem with base. – isolier May 15 '15 at 23:01