1

I'm a beginner at R and RStudio and I'm trying to make a frequency polygon on top of a histogram using the "cars" dataset.

attach(cars)
hist(speed)
lines(speed, lwd=2, col = "royalblue")

This is the output I'm getting.

What I need is the points coming properly on top of the histogram. I have seen this one using plots but I can't get to use it in my code.

This is the output I need (It's an example)

  • Does this answer your question? [Fitting a density curve to a histogram in R](https://stackoverflow.com/questions/1497539/fitting-a-density-curve-to-a-histogram-in-r) – jay.sf Jan 07 '20 at 18:16
  • @jay.sf It's close but the problem is that it's a density curve but I need a frequency polygon. [Here is what I hope to achieve](https://i.imgur.com/s6B7pcM.png) – Vaishnav Santhosh Jan 07 '20 at 19:37
  • Welcome to Stackoverflow. Please, see here how to make a great reproducible R example: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – cmirian Jan 07 '20 at 20:01
  • @VaishnavSanthosh Ah ok, didn't notice the difference, see answer. – jay.sf Jan 07 '20 at 20:02

2 Answers2

1

hist() has a hidden output which you can grab by assignment. Then feed lines() with it.

h <- hist(x, col=5)
lines(x=c(0, h$mids, tail(h$mids, 1) + el(diff(h$mids))), y=c(0, h$counts, 0), lwd=2)

enter image description here


Data:

set.seed(22522)
x <- rpois(50, 6)
jay.sf
  • 60,139
  • 8
  • 53
  • 110
0

Try

par(mfrow=c(2,2))
hist(speed)
lines(speed, lwd=2, col = "royalblue")

Alternatively, you can do it all at once in ggplot2. But I would need a data sample and your script.

Best

cmirian
  • 2,572
  • 3
  • 19
  • 59