使用 R 基础图形的堆叠直方图

Mic*_*jka 5 r histogram ggplot2

使用ggplot2它很容易创建堆叠直方图:

library(ggplot2)

ggplot(data = iris, aes(x = Sepal.Length, fill = Species)) + 
  geom_histogram(colour = 'white') 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ggplot(data = iris, aes(x = Sepal.Length, fill = Species)) + 
  geom_histogram(colour = 'white', position = 'fill')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我想知道如何仅使用R 基础图形创建两个直方图。

mto*_*oto 2

您可以根据和barplot()的频率表使用生成这两个图。SpeciesSepal.Length

# Create frequency table
tab <- table(iris$Species, iris$Sepal.Length)

# Stacked barplot
barplot(tab)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

# Stacked percent barplot
barplot(prop.table(tab, 2)) # Need to convert to marginal table first
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述