简体   繁体   English

X轴标签顺序GGPLOT

[英]Order of X-axis Labels GGPLOT

I have the following input data. 我有以下输入数据。

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"))

And want to create plots within ggplot that splits the data by type (so two sets of bar charts). 并希望在ggplot中创建按类型划分数据的图表(因此有两组条形图)。 I want the order of the bar charts to be grouped by the colours together. 我希望将条形图的顺序按颜色分组。 So below the right hand chart would group the blue and red bars to be next to each other. 因此,在右侧图表下方,会将蓝色和红色条形分组为彼此相邻。 I have a large number of variables so manually moving them around would not be an option. 我有大量的变量,因此手动移动它们将不是一种选择。 The code I used for the charts was: 我用于图表的代码是:

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)

在此处输入图片说明

I note that in different facets, the same city (x-axis variable) may be associated with different fill colours, which suggests that the order of variables could be different in each facet, in which case specifying its factor order won't work. 我注意到,在不同的方面中,相同的城市(x轴变量)可能与不同的填充色相关联,这表明变量在每个方面的顺序可能不同,在这种情况下,指定其因子顺序将无效。

Here's a workaround that specifies the x-axis order based on the fill variable, & adds a fake x-axis to the plot: 这是一个基于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