R Histogram Example Quick Reference



R Histogram Example Quick Reference

This article shows some R histogram examples.

Demo data

Weight data by sex:

set.seed(1234)
wdata = data.frame(
        sex = factor(rep(c("F", "M"), each=200)),
        weight = c(rnorm(200, 55), rnorm(200, 58))
        )

head(wdata, 4)
##   sex weight
## 1   F   53.8
## 2   F   55.3
## 3   F   56.1
## 4   F   52.7

R base plot

hist(wdata$weight, breaks = 30, col = "steelblue", frame = FALSE)

GGPlot2 package

library(ggplot2)
theme_set(theme_bw())
# Basic plot
ggplot(wdata, aes(x = weight)) +
  geom_histogram(bins = 30) 

# Change fill color by sex group
ggplot(wdata, aes(x = weight)) +
  geom_histogram(aes(fill = sex), bins = 30, alpha = 0.5,
                 position = position_dodge()) +
  scale_fill_viridis_d() 

GGPubr package

ggpubr: ggplot2-based publication ready plots

library(ggpubr)

# Basic plots
gghistogram(wdata, x = "weight", fill = "steelblue", alpha = 1)

# Change color by sex group
gghistogram(
  wdata, x = "weight", color = "sex",
  palette = c("#00AFBB", "#E7B800")
  )



Version: Français





No Comments

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments