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

时间:2016-08-17 10:50:18

标签: r histogram

我试图将x轴命名为正确。

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

但这会产生

enter image description here

我希望条形下方的字母不在顶部。

2 个答案:

答案 0 :(得分:2)

您必须在直方图bin中点绘制标签。如果您想要移除轴并且只有字母,padj会将字母移动到您刚刚移除的轴线附近。

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

答案 1 :(得分:1)

我通常认为barplot更适合分类变量。基数R的解决方案可能是,对数据进行一些重新排列:

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

输出如下:

enter image description here 既然你提到ggplot解决方案会很好:

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

输出为: enter image description here