[英]Reorder x values by factor in ggplot
假設我有以下命令生成 plot
mpg %>% filter(manufacturer == "toyota") %>%
ggplot( aes(x=model, y=hwy, fill=class)) +
theme(axis.text.x = element_text(angle = 20, hjust = 1)) +
geom_boxplot()
有沒有一種方法可以按因子對 x 標簽進行排序,以便所有具有相同 class 的箱線圖彼此相鄰出現?
謝謝!
我們可以使用factor
重新排序。 按“類”、“模型” arrange
數據,然后將“模型”轉換為factor
,將levels
指定為“模型”的unique
值並重新運行ggplot
library(dplyr)
library(ggplot2)
mpg %>%
filter(manufacturer == "toyota") %>%
arrange(class, model) %>%
mutate(model = factor(model, levels = unique(model))) %>%
ggplot( aes(x=model, y=hwy, fill=class)) +
theme(axis.text.x = element_text(angle = 20, hjust = 1)) +
geom_boxplot()
-輸出
另一個選項是fct_reorder
library(forcats)
mpg %>%
filter(manufacturer == "toyota") %>%
ggplot( aes(x=fct_reorder(model, class), y=hwy, fill=class)) +
theme(axis.text.x = element_text(angle = 20, hjust = 1)) +
geom_boxplot()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.