# geom_bar is designed to make it easy to create bar charts that show # counts (or sums of weights) g <- ggplot(mpg, aes(class)) # Number of cars in each class: g + geom_bar() # Total engine displacement of each class g + geom_bar(aes(weight = displ)) # To show (e.g.) means, you need stat = "identity" df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2)) ggplot(df, aes(trt, outcome)) + geom_bar(stat = "identity") # But geom_point() display exactly the same information and doesn't # require the y-axis to touch zero. ggplot(df, aes(trt, outcome)) + geom_point() # You can also use geom_bar() with continuous data, in which case # it will show counts at unique locations df <- data.frame(x = rep(c(2.9, 3.1, 4.5), c(5, 10, 4))) ggplot(df, aes(x)) + geom_bar() # cf. a histogram of the same data ggplot(df, aes(x)) + geom_histogram(binwidth = 0.5) # Bar charts are automatically stacked when multiple bars are placed # at the same location g + geom_bar(aes(fill = drv)) # You can instead dodge, or fill them g + geom_bar(aes(fill = drv), position = "dodge") g + geom_bar(aes(fill = drv), position = "fill") # To change plot order of bars, change levels in underlying factor reorder_size <- function(x) { factor(x, levels = names(sort(table(x)))) } ggplot(mpg, aes(reorder_size(class))) + geom_bar() Run the code above in your browser using DataLab