Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Label the x axis correct in a histogram in R

Tags:

r

histogram

I tried to name the x axis correct.

hist(InsectSprays$count, col='pink', xlab='Sprays', labels=levels(InsectSprays$spray), xaxt='n')
axis(1, at=unique(InsectSprays$spray), labels=levels(InsectSprays$spray))

But this produces

enter image description here

I want the letters below the bars and not on top.

like image 691
buhtz Avatar asked Sep 05 '25 17:09

buhtz


2 Answers

You have to plot the labels at the histogram bin midpoints. If you want to remove the axis and just have lettering, the padj will move the letters closer to the axis which you just removed.

h <- hist(InsectSprays$count, plot = FALSE)

plot(h, xaxt = "n", xlab = "Insect Sprays", ylab = "Counts",
     main = "", col = "pink")
axis(1, h$mids, labels = LETTERS[1:6], tick = FALSE, padj= -1.5)

enter image description here

like image 56
shayaa Avatar answered Sep 07 '25 08:09

shayaa


I generally think barplot are more suited for categorical variables. A solution in base R could be, with some rearrangement of the data:

d <- aggregate(InsectSprays$count, by=list(spray=InsectSprays$spray), FUN=sum)
d <- d[order(d$x, decreasing = T),]
t <- d$x
names(t) <- d$spray

barplot(t, las = 1, space = 0, col = "pink", xlab = "Sprays", ylab = "Count")

The output is the following:

enter image description here Since you mentioned a ggplot solution would be nice:

library(ggplot)
library(dplyr)

InsectSprays %>% 
    group_by(spray) %>% 
    summarise(count = sum(count)) %>% 
    ggplot(aes(reorder(spray, -count),count)) + 
    geom_bar(stat = "identity", fill = "pink2") +
    xlab("Sprays")

The output being: enter image description here

like image 37
thepule Avatar answered Sep 07 '25 08:09

thepule