Skip to content

Instantly share code, notes, and snippets.

@DavZim
Last active June 6, 2017 21:17
Show Gist options
  • Save DavZim/44dd68bb583d850a4a441a463e9c5a13 to your computer and use it in GitHub Desktop.
Save DavZim/44dd68bb583d850a4a441a463e9c5a13 to your computer and use it in GitHub Desktop.
# create some random data
set.seed(123)
x <- rpois(100, lambda = 100)
# approach 1: hard to compare due to different aspect ratios
hist(x, breaks = c((min(x) - 1):(1 + max(x))))
plot(table(x), main = "Barplot of x")
# approach 2: easier to compare
library(dplyr)
library(ggplot2)
df1 <- data_frame(x)
df2 <- df1 %>% group_by(x) %>% summarise(n = n())
table_x <- table(x)
df3 <- data_frame(x = names(table_x) %>% as.numeric(),
n = as.numeric(table_x))
hist_x <- hist(x, plot = F, breaks = c(min(x):max(x)))
df4 <- data_frame(x = hist_x$mids,
n = hist_x$counts)
ggplot() +
geom_col(data = df2, aes(x = x, y = n), fill = "blue",
alpha = 0.25) +
geom_col(data = df3, aes(x = x, y = n), fill = "red",
alpha = 0.25) +
geom_col(data = df4, aes(x = x, y = n), fill = "green",
alpha = 0.25) +
geom_histogram(data = df1, aes(x = x), bins = 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment