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,Sepal.Length))+geom_point()

plot of chunk unnamed-chunk-1

Additional Features

Add Groups/Colors

ggplot(iris,aes(Sepal.Width,Sepal.Length,color=Species))+geom_point()

plot of chunk unnamed-chunk-2

Increase Size

ggplot(iris,aes(Sepal.Width,Sepal.Length,color=Species))+geom_point(size=4)

plot of chunk unnamed-chunk-3

Variable Size

ggplot(iris,aes(Sepal.Width,Sepal.Length,color=Species,size=Petal.Length))+geom_point()

plot of chunk unnamed-chunk-4

Aesthetics

Add Outlines to points

Here the key is to use shape=21 or pch=21. Values from 21-25 in the shape or pch parameter will separately specify the fill and color argument

ggplot(iris,aes(Sepal.Width,
                Sepal.Length,
                size=Petal.Length,
                fill=Species))+     # Change Fill color based on Species
  geom_point(shape=21,              # Set shape/pch to be circle with outline
             color='black',         # Set outline to be black
             alpha=0.8)             # Add some transparency

plot of chunk unnamed-chunk-5

Changing Themes

Modify Axes

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

ggplot(iris,aes(Sepal.Width,
                Sepal.Length,
                size=Petal.Length,
                fill=Species))+     # Change Fill color based on Species
  geom_point(shape=21,              # Set shape/pch to be circle with outline
             color='black',         # Set outline to be black
             alpha=0.8)+            # Add some transparency
  scale_x_continuous('Sepal Width')+          # Add label to x-axis
  scale_y_continuous('Sepal Length')+         # Add label to y-axis
  scale_fill_discrete('Iris Species')+        # Add label to Legend
  scale_size_continuous('Petal Length')+      # Add Label to Legend
  standard_theme                            # Modify axis/legend element size

plot of chunk unnamed-chunk-6

More Resources