R语言相对频率直方图:如何将柱数从10修改为7?
How to Adjust R Histogram to Show 7 Bins Instead of 10
Hey there! Let's tweak your code to get exactly 7 bins in your relative frequency histogram. Here's what you need to do:
The Key Fix: Use the breaks Parameter in hist()
The default behavior of R's hist() function is to auto-calculate the number of bins (which gave you 10). To force it to use 7 bins, just add the breaks=7 argument when creating your histogram object. Also, there's a small typo in your axis() call that we'll fix to make the x-axis labels align correctly.
Modified Full Code
# Generate histogram with exactly 7 bins histo <- hist(DatosTA1$Datos, breaks = 7) # Create relative frequency bar plot (dividing by 50 since your sample size n=50) barplot(histo$counts/50, col = "green", space = 0) -> bp # Fix x-axis: use barplot positions (bp) and histogram midpoints as labels axis(1, at = bp, labels = round(histo$mids, 2)) # Add axis labels and title title(ylab = "Frecuencia relativa", xlab = "Distribución de frecuencias del tiempo relativo")
Extra Details & Customization
- Why
breaks=7? This tellshist()to split your data into 7 equal-width intervals, resulting in 7 bars. - Axis Fix: Your original
axis(1,at=b,labels=b)had an undefined variableb—usingat=bp(from thebarplotoutput) ensures the x-axis ticks line up with the bars, andhisto$midsgives you the midpoint of each bin (rounded to 2 decimals for readability). - Manual Bin Control (Optional): If you want precise control over bin ranges instead of equal-width bins, define custom breakpoints. For example, to span from your data's min to max with 7 bins:
custom_breaks <- seq(min(DatosTA1$Datos), max(DatosTA1$Datos), length.out = 8) # 7 bins need 8 breakpoints histo <- hist(DatosTA1$Datos, breaks = custom_breaks)
内容的提问来源于stack exchange,提问作者viviana selenia
相关产品推荐
相关产品推荐

