以编程方式在各个方面设置各个轴的限制

时间:2019-07-23 16:46:40

标签: r ggplot2 limit axis facet-grid

我需要如下所述在不同方面设定各个x轴限制的帮助。

首选编程方式,因为我会将相同的模板应用于不同的数据集。

  • 前两个小面将具有相同的x轴限制(以具有可比的条形图)
  • 最后一个方面( performance )的限制在0到1之间,因为它是按百分比计算的

我看过this和其他一些相关问题,但是无法将其应用于我的数据。

谢谢。

df <- 
  data.frame(
    call_reason = c("a","b","c","d"),
    all_records = c(100,200,300,400),
    problematic_records = c(80,60,100,80))
df <- df %>% mutate(performance = round(problematic_records/all_records, 2))


df
    call_reason all_records problematic_records performance
               a         100                  80        0.80
               b         200                  60        0.30
               c         300                 100        0.33
               d         400                  80        0.20

df %>% 
  gather(key = facet_group, value = value, -call_reason)  %>% 
  mutate(facet_group = factor(facet_group,
  levels=c('all_records','problematic_records','performance'))) %>% 
  ggplot(aes(x=call_reason, y=value)) +
  geom_bar(stat="identity") + 
  coord_flip() +
  facet_grid(. ~ facet_group)

enter image description here

1 个答案:

答案 0 :(得分:1)

因此,这是将facet_grid(scales = "free_x")geom_blank()结合使用的一种方法。在将其通过管道传输到ggplot之前,请考虑将df作为您的df

ggplot(df, aes(x=call_reason, y=value)) +
  # geom_col is equivalent to geom_bar(stat = "identity")
  geom_col() +
  # geom_blank includes data for position scale training, but is not rendered
  geom_blank(data = data.frame(
    # value for first two facets is max, last facet is 1
    value = c(rep(max(df$value), 2), 1),
    # dummy category
    call_reason = levels(df$call_reason)[1],
    # distribute over facets
    facet_group = levels(df$facet_group)
    )) +
  coord_flip() +
  # scales are set to "free_x" to have them vary independently
  # it doesn't really, since we've set a geom_blank
  facet_grid(. ~ facet_group, scales = "free_x")

enter image description here

只要您的列名保持不变,这应该起作用。

编辑:

要重新排序call_reason变量,可以在ggplot的管道中添加以下内容:

df %>% 
  gather(key = facet_group, value = value, -call_reason)  %>% 
  mutate(facet_group = factor(facet_group,
                              levels=c('all_records','problematic_records','performance')),
         # In particular the following bit:
         call_reason = factor(call_reason, levels(call_reason)[order(value[facet_group == "performance"])]))