Ivn Bubrov
Ivn Bubrov

Reputation: 43

ggplot or qplot histogram in R

I know this is pretty much a basic question, but I have some trouble in drawing histograms from a single vector containing these numbers (dat):

30.90 31.00 32.75 32.65 32.50 31.60 31.80 30.70 31.20 28.10 29.50 28.60 31.70 33.10

The qplot is straight forward:

qplot(PorData,  binwidth=1.0, geo="histogram", xlab="Data", ylab="Frequency") 

This gives me a default histogram: enter image description here

I would love to do a bit more aesthetically pleasing histogram, which would also contain a density curve showing the skewness of the data and to change the bin colors with a black outline, somewhat like this one: enter image description here

Is it better to use the qplot function or the ggplot? Thanks in advance!

Upvotes: 3

Views: 3966

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

Here's an approach to create a histogram together with a density curve in ggplot2.

The data:

dat <- scan(textConnection("30.90 31.00 32.75 32.65 32.50 31.60 31.80 30.70 31.20 28.10 29.50 28.60 31.70 33.10"))

The plot:

library(ggplot2)
qplot(dat,  binwidth = 1.0, geom = "histogram", xlab = "Data", ylab = "Frequency",
      y = ..density.., fill = I("white"), colour = I("black")) +
  stat_density(geom = "line")

Here, y = ..density.. is used to use relative frequencies on the y axis.

enter image description here

Upvotes: 3

Related Questions