How could I go on with the plot?

Hi,
Continuous variables are divided and frequencies counted in different interval, histograms are drawn, and probability density curves are fitted.
The horizontal coordinates are of the form of different intervals [a,b). Now it seems that the graph I made has problems with both the horizontal coordinates ( no scale lines)and vertical coordinates.
You could also use other data to show your opinion.
Thank you for your help in advance.

set.seed(123)
data <- rnorm(1000, mean = 50, sd = 10)
# 将x分为5个区间
cuts <- cut(data, breaks = c(0, 20, 40, 60, 80, 100), right = FALSE)

# 计算各个区间的频次
freqs <- table(cuts)

# 绘制直方图和概率密度曲线
barplot(freqs, names = c("[0,20)", "[20,40)", "[40,60)", "[60,80)", "[80,100)"))
lines(data, col = "red")

Created on 2023-04-09 with reprex v2.0.2

Do you have a reason not to use the built-in R functions?

set.seed(123)
data <- rnorm(1000, mean = 50, sd = 10)


hist(data, freq = FALSE)
lines(density(data), col = 'red3')
1 Like

@AlexisW Thank you for your help. I got the following picture using your code. While how could I change the labels of x-axis? As it shows, every bar in the plot has a corresponding interval [a, b), values of a and b are different between every bar. Is it possible to show them in x-axis? And not show the breaks value.


Maybe like this and then adds the density line.

somewhat handcrafted, but its better than nothing ?


set.seed(123)
data <- rnorm(1000, mean = 50, sd = 10)


h1<-hist(data, freq = FALSE, xaxt = "n")

mybreaks <- h1$breaks
names(mybreaks) <- paste0("[",mybreaks,":",c(tail(mybreaks,-1),NA),"]")
mybreaks <- c(15,mybreaks)
axis(side=1,line=-.4, tck=0,at=mybreaks+2.5,labels = names(mybreaks),cex.axis=.5)
lines(density(data), col = 'red3')

image

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.