问题
Using ggplot2
it is very easy to create stacked histograms:
library(ggplot2)
ggplot(data = iris, aes(x = Sepal.Length, fill = Species)) +
geom_histogram(colour = 'white')
ggplot(data = iris, aes(x = Sepal.Length, fill = Species)) +
geom_histogram(colour = 'white', position = 'fill')
I would like to know how to create both histograms using only R base graphics.
回答1:
You can generate both plots with barplot()
, based on a frequency table of Species
and Sepal.Length
.
# Create frequency table
tab <- table(iris$Species, iris$Sepal.Length)
# Stacked barplot
barplot(tab)
# Stacked percent barplot
barplot(prop.table(tab, 2)) # Need to convert to marginal table first
来源:https://stackoverflow.com/questions/37365397/stacked-histograms-using-r-base-graphics