簡體   English   中英

X軸標簽順序GGPLOT

[英]Order of X-axis Labels GGPLOT

我有以下輸入數據。

sample_data <- data.frame(city = c("a", "b", "c","d", "a", "b", "c", "d"), value = c(10, 11, 17, 12, 13, 14, 11, 8), type = c(1,1,1,1,2,2,2,2), country = c("c1", "c2", "c1", "c1", "c2", "c2", "c1", "c1"))

並希望在ggplot中創建按類型划分數據的圖表(因此有兩組條形圖)。 我希望將條形圖的順序按顏色分組。 因此,在右側圖表下方,會將藍色和紅色條形分組為彼此相鄰。 我有大量的變量,因此手動移動它們將不是一種選擇。 我用於圖表的代碼是:

sample_data <- sample_data %>% 
     mutate(city2 = factor(city, levels=city[order(country)]))
ggplot(sample_data) + 
    geom_col(aes(x=city2, y=value, colour=country, fill=country)) + facet_wrap(~type)

在此處輸入圖片說明

我注意到,在不同的方面中,相同的城市(x軸變量)可能與不同的填充色相關聯,這表明變量在每個方面的順序可能不同,在這種情況下,指定其因子順序將無效。

這是一個基於fill變量指定x軸順序的解決方法,並向繪圖添加了虛假的x軸:

library(dplyr)

sample_data <- sample_data %>%
  group_by(type) %>%
  arrange(country) %>%
  mutate(x = row_number()) %>%
  ungroup()

ggplot(sample_data,
       aes(x = x, y = value, fill = country, label = city)) +
  geom_col() +
  geom_text(aes(y = 0), nudge_y = -1) +      # fake x-axis
  facet_wrap(~type) +
  theme(axis.text.x = element_blank(),       # hide x-axis labels
        axis.ticks.x = element_blank(),      # hide x-axis tick marks
        panel.background = element_blank())  # white background for easier reading

在此處輸入圖片說明

暫無
暫無

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

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