Waldir Leoncio
Waldir Leoncio

Reputation: 11341

How can I express densities as percentages in R?

When I run a density histogram in R, the vertical axis shows densities as fractions. Try this, for example: hist(rnorm(100), freq = FALSE)

See how the vertical axis shows "0.0", "0.1", "0.2", etc. How can I make it display "0%", "1%", "2%"?

Upvotes: 3

Views: 5092

Answers (2)

Hong Ooi
Hong Ooi

Reputation: 57686

Don't plot the vertical axis in hist. Add it yourself via axis.

h <- hist(rnorm(100))
plot(h, freq=FALSE, yaxt="n")
axis(2, pretty(h$density), sprintf("%0.0f%%", pretty(h$density)*100))

However, this is really misleading, because densities aren't the same as percentages or proportions of something. If you were to do something like

hist(rnorm(100, s=0.1))

You get the same distribution, but now all your densities are 10 times larger in magnitude because the scale of the distribution is 10 times smaller.

It would make more sense to plot the cumulative frequency polygon or histogram with percentages on the y-axis.

Upvotes: 1

Roman Luštrik
Roman Luštrik

Reputation: 70643

Something like this?

x <- rnorm(100)
par(mfrow = c(1, 2))
hist(x, freq = FALSE, axes = FALSE)
axis(2, at = seq(0, 0.4, 0.1), labels = paste(0:4, "%", sep = ""))
hist(x, freq = FALSE)

enter image description here

Upvotes: 3

Related Questions