You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 tells hist() 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 variable b—using at=bp (from the barplot output) ensures the x-axis ticks line up with the bars, and histo$mids gives 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:37:54