在R的直方图中将x轴标记为正确

问题描述:

我试图正确命名x轴.

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

但这会产生

我希望字母在条形下方,而不是在顶部.

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

我通常认为barplot更适合分类变量.重新布置了数据后,可以在基数R中得到一个解决方案:

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")

输出如下:

既然您提到了ggplot解决方案,那就太好了:

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")

输出为: