In [1]:
# Let us create the humble dataset
areas <- c("North", "East", "West", "South", "Central")
sales <- c(5, 25, 15, 20, 10)
profit <- c(2, 8, 6, 5, 3)
In [2]:
# For maps
lat <- c(0, 1, -1, 0, 0)
lon <- c(1, 0, 0, -1, 0)
In [3]:
humble <- data.frame(areas, sales, profit, lat, lon)
In [6]:
head(humble)
Out[6]:
In [7]:
humble$areas <- factor(humble$areas,
levels = c("North", "East",
"West", "South",
"Central"))
In [8]:
str(humble)
Created by Hadley Wickham. Based on the book - "The Grammar of Graphic" by Leland Wilkinson
Grammar: “the fundamental principles or rules of an art or science”
"…rules for constructing graphs mathematically and then representing them as graphics aesthetically."
Main arguments
General ggplot syntax
ggplot(data) + aes(…) + geom_x() + … + stat_x + …
Layer specifications
geom*(mapping, data, …, geom, position) stat*(mapping, data, …, stat, position) Additional components: scales, coordinates, facet
In [9]:
library(ggplot2)
In [16]:
head(humble)
Out[16]:
In [19]:
ggplot(data = humble) +
aes(x = areas, weight=sales, fill = profit) +
geom_bar(width=1)
In [12]:
ggplot(humble) + aes(areas, weight = sales, fill = profit) + geom_bar()
In [13]:
ggplot(humble) + aes(areas, weight = sales, fill = profit) + geom_bar() + coord_flip()
In [14]:
ggplot(humble) + aes(areas, weight = sales, fill = profit) + geom_bar(width = 1) + coord_polar()
In [20]:
ggplot(humble)
+ aes(areas, weight = sales, fill = profit)
+ geom_bar(width = 1)
+ coord_polar(theta = "y")
In [21]:
ggplot(humble) + aes(areas, weight = sales, fill = areas) + geom_bar() +
geom_point(aes(areas, profit), size = 5) + coord_flip()
In [22]:
ggplot(humble) + aes(areas, weight = sales, fill = areas) + geom_bar(width = 1) +
geom_point(aes(areas, profit), size = 5) + coord_polar(theta = "y")
In [ ]:
library(dplyr)
library(tidyr)
In [ ]:
humbleTall <- humble %>%
gather("metric", "value", 2:3)
In [ ]:
humbleTall
In [ ]:
ggplot(humbleTall) + aes(areas, weight = value, fill = metric) + geom_bar(position = 'dodge')
In [ ]:
ggplot(humbleTall) + aes(areas, weight = value, fill = metric) + geom_bar(position = 'dodge') +
coord_polar(theta = "y")
In [ ]:
ggplot(humbleTall) + aes(areas, weight = value, fill = metric) +
geom_bar(alpha = 0.3, width = 1, position = "identity")
In [ ]:
ggplot(humbleTall) + aes(areas, weight = value, fill = metric) +
geom_bar(alpha = 0.3, width = 1, position = "identity") + coord_polar()
In [ ]:
ggplot(humble) + aes(sales, profit, color = profit/sales) + geom_point()
In [ ]:
ggplot(humble) + aes(sales, profit, size = profit/sales, color = areas) + geom_point()
In [ ]:
ggplot(humble) + aes(sales, profit, size = profit/sales, color = areas) + geom_point() + coord_polar()
In [ ]:
ggplot(humble) + aes(lon, lat, size = sales, color = profit/sales) + geom_point() + coord_map()
In [ ]: