How to Create a Histogram from Aggregated Data in R

How can I create a histogram from aggregated data in R?

To get this kind of flexibility, you may have to replicate your data. Here is one way of doing it with rep:

n <- 10
dat <- data.frame(
x = sort(sample(1:50, n)),
f = sample(1:100, n))
dat

expdat <- dat[rep(1:n, times=dat$f), "x", drop=FALSE]

Now you have your data replicated in the data.frame expdat, allowing you to call hist with different numbers of bins:

par(mfcol=c(1, 2))
hist(expdat$x, breaks=50, col="blue", main="50 bins")
hist(expdat$x, breaks=5, col="blue", main="5 bins")
par(mfcol=c(1, 1))

Sample Image

Create histogram from summarized data R

You need a barplot.

Height = c(4,17,12,6)
Bins = c("0-19", "20-39", "40-59", "60-99")
barplot(Height, names.arg=Bins)

Barplot

barplot has many parameters that you might consider adjusting to make this prettier.

how create histogram from data frame in R

you can do

hist(df$col1)

or

with(df, hist(col2))

If you want all the columns each in their own histograms you could perhaps do something like

par(mfrow=c(2,1))
histout=apply(df,2,hist)

How to create a histogram for every column in a data set on a separate page

Simply call the pdf() function then use a for loop to iterate over each column:

pdf('plots.pdf')
for(i in 1:length(df)){
ggplot(data = df) +
geom_histogram(mapping = aes(x = df[,i]), bins = 4)
}
dev.off()

Creating a histogram in R knowing bin heights

This is just a one-liner after having the data set read in.

barplot(as.matrix(df1[-1]))

Sample Image



Data

df1 <- read.table(text = "
Interval 0-2 2-4 4-6 6-10 10-15 15-25 >25
'Number of observations' 6 9 7 9 6 7 5
", header = TRUE, check.names = FALSE)


Related Topics



Leave a reply



Submit