干猕猴桃
干猕猴桃

Reputation: 305

R histogram add label with percentage instead of rough values

I want to use hist() to make a histogram using percentages.

However, I also want to place a label at the top of each histogram bar showing the actual percentage.

Here is my code and a link to the output:

DataToPlot <- sapply(dataframe, as.numeric)

hist(DataToPlot, xlab="dataframe",ylab="Calls", main="Weekly data", col="lightgreen",labels = TRUE, ylim=c(0, 12000))

enter image description here

Upvotes: 1

Views: 992

Answers (3)

RoB
RoB

Reputation: 1984

What you want is the freq = FALSE option. @jkd got it the wrong way round. Note the doc says

freq : logical; if TRUE, the histogram graphic is a representation of frequencies, the counts component of the result; if FALSE, probability densities, component density, are plotted (so that the histogram has a total area of one). Defaults to TRUE if and only if breaks are equidistant (and probability is not specified).

If you only want to use base graphics, this is as good as you're going to get with just the hist() function. You can add the percentage values manually like so

data(iris)

# store the histogram in 'h'
h <- hist(iris$Sepal.Length, xlab="dataframe", ylab="Calls", freq = FALSE, 
          main="Weekly data", col="lightgreen", labels = FALSE, ylim = c(0,0.5))


text(
     x = (h$breaks[-1] + h$breaks[-length(h$breaks)])/2, # compute break center
     y = h$density, # use density as y value
     labels = paste(round((h$density/sum(h$density))*100, 2), "%"), # labels are (density/sum(density)) *100 for %
     pos = 3) # pos = 3 means above the specified coordinates

This yields enter image description here

Note that the data I used is from the iris dataset since you didn't give any

Upvotes: 3

Mario
Mario

Reputation: 2621

Add this line (value is the column you would like to have as lables):

labs <- paste(round(DataToPlot$value), "%", sep="")

And call the plot like this:

hist(DataToPlot, xlab="dataframe",ylab="Calls", main="Weekly data", col="lightgreen",labels = labs, ylim=c(0, 12000))

Upvotes: 1

jkd
jkd

Reputation: 1654

Use the freq = TRUE option:

hist(DataToPlot, xlab="dataframe",ylab="Calls", main="Weekly data", col="lightgreen",labels = TRUE, ylim=c(0, 12000), freq = TRUE)

Upvotes: 1

Related Questions