簡體   English   中英

在ggplot中按因子重新排序x值

[英]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.

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