簡體   English   中英

在R中的直方圖中標記x軸正確

[英]Label the x axis correct in a histogram in R

我試圖將x軸命名為正確。

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

但這會產生

在此輸入圖像描述

我希望條形下方的字母不在頂部。

您必須在直方圖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)

在此輸入圖像描述

我一般認為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")

輸出如下:

在此輸入圖像描述 既然你提到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")

輸出是: 在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM