Saturday, July 9, 2011

R ggplot - barplot

barplot

  • load the package ggplot2 and the diamond data
  • first we create a object p of class ggplot, where we map clarity to x (horizontal position)
p <- ggplot(diamonds, aes(x=clarity))
summary(p)
data: carat, cut, color, clarity, depth, table, price, x, y, z
  [53940x10]
mapping:  x = clarity
faceting: facet_grid(. ~ ., FALSE)
  • p contains all information ggplot needs to build a barplot, all we have to do is adding a layer with geom="bar";
p + layer(geom="bar")

  • to this simple barplot we can add the following (optional) aesthetics:
    • colour: color of the borders of the bins
    • fill: color of the filling
    • size:
    • linetype: line type of the borders
    • weight:
    • alpha: transparency of fill [0,1]
p + layer(geom="bar", geom_params=list(fill="steelblue", colour="black", linetype=4, alpha=0.3))

  • but a barplot can visualize more information about the data - so we add a new mapping to p
p <- ggplot(diamonds, aes(x=clarity, fill=color)) # where color is the variable of the dataframe diamonds
  • now the default output looks like:
p + layer(geom="bar")

  • the plot can be customized by the same aesthetics, fill would override the aesthetic mapping of p
  • additional we can add a position adjustment
p + layer(geom="bar", position="dodge") 

  • or
p + layer(geom="bar", position="fill") 

  • if we flip (coordflip()) the underlying coordinate system, we can rotate the plot
p + layer(geom="bar", position="stack") + coord_flip()

  • or we even can change the coordinate system to polar coordinates:
p + layer(geom="bar", position="stack") + coord_polar()

No comments :

Post a Comment