[英]frequency plot for binned data
我已将数据分类为各种大小,并希望为给定的花瓣长度范围内的每个物种制作一个刻面频率 plot(每个大小箱的直方图类似于所附图片)。
library(ggplot2)
br = seq(1,6,by=0.4)
df1 = iris
df = as.data.frame(with(df1, table(spe = df1$Species,
pl =cut(df1$Petal.Length, br, include.lowest = TRUE))))
ggplot(df, aes(x = pl, y = Freq)) + geom_bar(stat = "identity")
我怎样才能做到这一点? 我在设置 x 轴时遇到问题,因为我希望它是连续的,而 plot 它被装箱了。
这是一种使用facet_wrap
的方法。 我们可以使用stringr
中的str_replace_all
来改善轴标签的外观。
library(ggplot2)
library(stringr)
ggplot(df, aes(x = pl, y = Freq, fill = spe)) +
geom_bar(stat = "identity") +
scale_x_discrete(labels = function(x)
str_replace_all(x, regex(c("[\\(\\[]" = "", "," = " - ", "\\]" = "")))) +
facet_wrap(.~spe, ncol = 1) +
theme(axis.text.x=element_text(angle = 45, hjust = 1))
另一种方法是使用geom_histogram
:
ggplot(df1, aes(x = Petal.Length, fill = Species)) +
geom_histogram(color = "white", bins = 20) +
facet_wrap(.~Species, ncol = 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.