簡體   English   中英

R ggplot條形圖

[英]R ggplot bar chart

考慮以下代碼:

d <- data.frame(y = sample(LETTERS[1:8]), x = c(-1.6,-1.4,-1.2,0,0,1.2,1.3,1.4), stringsAsFactors = FALSE)

ggplot(d, aes(y=x, x=y)) + geom_bar() + coord_flip()

誰能告訴我如何強制 ggplot 不按字母順序排列數據? 我使用了stringsAsFactors = FALSE以便我的字符不是factor類型。 此外,為什么我必須將 x 和 y 從aes(y=y, x=x)交換為aes(y=x, x=y)我的 y 數據與 y 軸一起繪制? 那是因為我使用了coord_flip()選項嗎?

這是一個解決方法:

ggplot(d, aes(y=x, x=factor(y, levels=y))) + ...

軸按字母順序排列的原因是geom_barx變量轉換為factor factor默認levels將按字母順序排列,因此您需要告訴 R 否則。

coord_flip的原因是geom_barx變量視為 bin 並將y變量視為值。

暫無
暫無

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

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