Now, let's use qplot
to produce a frequency bar chart; in this case, for the categorical variable TREATMENT
. The heights of the bars give the counts of patients receiving each treatment. We choose a nice hue of brown from the Hexadecimal Color Chart. To create a bar chart, we use geom = "bar"
. Enter the following syntax:
qplot(TREATMENT, data = T, geom = "bar", binwidth = 5, xlab = "HEIGHT (cm)", ylab = "FREQUENCY", fill = I("#CC6600"), color = I("blue"))
Here is our bar chart:
The following is a more complex example involving bar charts. We set up a new dataset relating to dinners purchased by two people at fast food outlets during one week. Enter the following syntax into R:
dinners = data.frame(person=c("Thomas", "Thomas", "Thomas", "James", "James"), meal = c("curry", "stew", "salad", "fish", "stir-fry"), price = c(15, 18, 12, 25, 13)) dinners
The output is as follows:
person meal price 1 Thomas curry 15 2 Thomas stew 18 3 Thomas salad 12 4 James fish 25 5 James stir-fry 13
Let's plot the number of dinners each person purchased that week. We choose a nice hue of purple from the Hexadecimal Color Chart. Enter the following syntax:
qplot(person, data = dinners, geom = "bar", ylab = "Meals", fill = I("#9999CC"))
Here is our bar chart of the number of dinners:
By default, the height of each bar gives a count of the number of dinners purchased by each person. However, if we want to graph the total cost of each person's dinners, we must provide a different weight; in this case, the price variable. The weight is simply the variable that we wish to evaluate and plot on our bar graph. We choose a nice hue of green. Enter the following syntax:
qplot(person, weight = price, data = dinners, fill = I("#009933"), geom = "bar", ylab = "Total Cost ($)")
The bar chart now looks like the following:
Now the height of each bar represents the total cost of each person's dinners.