Rob Weyant bio photo

Rob Weyant

Data Scientist at Powerley

Twitter LinkedIn Instagram Github Last.fm

Basic Syntax

library(ggplot2)
ggplot(iris,aes(Sepal.Width))+geom_histogram()
`stat_bin()` using `bins = 30`. Pick better value with
`binwidth`.

plot of chunk unnamed-chunk-1

Additional Features

Add Groups

ggplot(iris,aes(Sepal.Width,fill=Species))+geom_histogram()
`stat_bin()` using `bins = 30`. Pick better value with
`binwidth`.

plot of chunk unnamed-chunk-2

Fix Binwidth

ggplot(iris,aes(Sepal.Width,fill=Species))+geom_histogram(binwidth=.10)

plot of chunk unnamed-chunk-3

As a Density

ggplot(iris,
       aes(Sepal.Width,fill=Species))+geom_histogram(aes(y=..density..))
`stat_bin()` using `bins = 30`. Pick better value with
`binwidth`.

plot of chunk unnamed-chunk-4

Aesthetics

Add Outlines to Bars

ggplot(iris,aes(Sepal.Width,fill=Species))+
  geom_histogram(binwidth=.1,    # Fixed Bin-width
                 alpha=0.7,      # Make Slightly transparent
                 color='black',  # Add Outline
                 size=0.4)       # Thickness of Outline

plot of chunk unnamed-chunk-5

Modify Axes

ggplot(iris,aes(Sepal.Width,fill=Species))+
  geom_histogram(binwidth=.1,alpha=0.7,color='black',size=0.4) +
  scale_x_continuous('Sepal Width')+          # Add label to x-axis
  scale_y_continuous('Count')+                # Add label to y-axis
  scale_fill_discrete('Iris Species')+        # Add label to legend
  theme(axis.text.x=element_text(size=14),    # Change x-axis value text-size
        axis.title.x=element_text(size=18),   # Change x-axis label text-size
        axis.text.y=element_text(size=14),    # Change y-axis value text-size
        axis.title.y=element_text(size=18),   # Change y-axis label text-size
        legend.text=element_text(size=14),    # Change legend value text-size
        legend.title=element_text(size=16))   # Change legend title text-size

plot of chunk unnamed-chunk-6

More Resources