buhtz
buhtz

Reputation: 12152

Label the x axis correct in a histogram in R

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.

Upvotes: 4

Views: 43248

Answers (2)

shayaa
shayaa

Reputation: 2797

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

Upvotes: 8

thepule
thepule

Reputation: 1751

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

Upvotes: 2

Related Questions