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))
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
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]))
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
Locator Equivalent in Ggplot2 (For Maps)
Understanding Ddply Error Message - Argument "By" Is Missing, with No Default
Drawing a Tangent to the Plot and Finding the X-Intercept Using R
2 Knitr/R Markdown/Rstudio Issues: Highcharts and Morris.Js
Converting a "Map" Object to a "Spatialpolygon" Object
Using Rollmean When There Are Missing Values (Na)
Loading Dplyr After Plyr Is Causing Issues
Compute All Pairwise Differences Within a Vector in R
Error When Plotting Sf Object --- Error: Could Not Find Function "Geom_Sf"
R: How to Find What S3 Method Will Be Called on an Object
How to Reverse Legend (Labels and Color) So High Value Starts at Bottom
Replace Nas with Mean of the Same Column of a Data.Table
Converting a Data.Frame to a List of Lists
Pivot_Wider, Count Number of Occurrences
Flexdashboard - Change Title Bar Color
Use Csl-File for PDF-Output in Bookdown
Ggplot2 One Line Per Each Row Dataframe
Testthat Fails Within Devtools::Check But Works in Devtools::Test