Last active
April 1, 2016 20:07
-
-
Save lovrot/87dc6927cf6162e9cb78 to your computer and use it in GitHub Desktop.
[ggplot2] Billiard ball "geom" with aestetics for factors - numbers in symbols
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
ggplot2::theme_set(theme_classic()) | |
## Create a dataframe with dummy data | |
set.seed(123) | |
n <- 20 | |
n_categories <- 5 | |
df <- data.frame( | |
x = 1:n + rnorm(n), | |
y = 1:n + rnorm(n), | |
category = sample(factor(letters[1:n_categories]), size = n, replace = TRUE)) | |
summary(df) | |
## Create an initial graph | |
gg <- ggplot(data = df, aes(x = x, y = y, col = category, label = as.integer(category))) + | |
geom_point(shape = 19, size = 6) + | |
geom_text(col = "white", size = 3) | |
plot(gg) | |
## Problem | |
## ------- | |
## How can we get numbers in the symbols in the figure legend? | |
## | |
## Solution | |
## -------- | |
## The philosophy in the Grammar of Graphics and ggplot is that we map | |
## abstract data to things we can perceive with our senses, aestetics. | |
## The solution to the problem is to think about the numbers as shapes | |
## and not text, and then define your own mapping from category to shape. | |
## Define a mapping for the shapes on the billiard balls, i.e. the numbers on the balls | |
shapes_category <- as.character(1:length(levels(df$category))) | |
names(shapes_category) <- levels(df$category) | |
shapes_category | |
## Create a revised version of the graph | |
gg <- ggplot(data = df, aes(x = x, y = y)) + | |
geom_point(aes(col = category), shape = 19, size = 6) + | |
geom_point(aes(shape = category), col = "white", size = 3) + | |
scale_shape_manual(values = shapes_category) | |
plot(gg) | |
## For fun, here's an alternative version | |
gg <- ggplot(data = df, aes(x = x, y = y)) + | |
geom_point(aes(col = category), shape = 21, fill = "white", size = 6, stroke = 2) + | |
geom_point(aes(shape = category), col = "black", size = 3) + | |
scale_shape_manual(values = shapes_category) | |
plot(gg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment