简体   繁体   中英

frequency plot for binned data

I have binned the data to various size and would like to make a facet frequency plot for each species for a given range of petal length(a histogram for each size bin something like in the attached pic).

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")

想要的情节

How can I do this? I am having issue with setting the x axis as I want it continuous and plot it binned.

Here is an approach with facet_wrap . We can use str_replace_all from stringr to improve the appearance of the axis labels.

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))

在此处输入图像描述

An alternative approach would be to use geom_histogram :

ggplot(df1, aes(x = Petal.Length, fill = Species)) + 
  geom_histogram(color = "white", bins = 20) + 
  facet_wrap(.~Species, ncol = 1)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM