Stacked Histograms Using R Base Graphics

吃可爱长大的小学妹 提交于 2020-01-15 03:53:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!