在R的直方图中将x轴标记为正确 [英] Label the x axis correct in a histogram in R
本文介绍了在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")
输出为:
这篇关于在R的直方图中将x轴标记为正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文