R 以编程方式设置镶嵌面中的各个轴限制

R 以编程方式设置镶嵌面中的各个轴限制,r,ggplot2,limit,axis,facet-grid,R,Ggplot2,Limit,Axis,Facet Grid,我需要帮助设置不同面上的单个x轴限制,如下所述 首选编程方法,因为我将对不同的数据集应用相同的模板 前两个面将具有相同的x轴限制(具有可比较的条) 最后一个方面的(性能)限制将介于0和1之间,因为它是以百分比计算的 我已经看到和其他一些相关的问题,但无法将其应用到我的数据中 提前谢谢 df <- data.frame( call_reason = c("a","b","c","d"), all_records = c(100,200,300,400), p

我需要帮助设置不同面上的单个x轴限制,如下所述

首选编程方法,因为我将对不同的数据集应用相同的模板

  • 前两个面将具有相同的x轴限制(具有可比较的条)
  • 最后一个方面的(性能)限制将介于0和1之间,因为它是以百分比计算的
我已经看到和其他一些相关的问题,但无法将其应用到我的数据中

提前谢谢

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)
df%
聚集(键=面\组,值=值,-调用\原因)%>%
突变(小平面组=因子(小平面组,
级别=c('all_records'、'problem_records'、'performance'))%>%
ggplot(aes(x=调用原因,y=值))+
几何图形栏(stat=“identity”)+
coord_flip()+
面网格(.~facet\u组)

因此,这里有一种方法可以使用
facet\u grid(scales=“free\u x”)
,结合
geom\u blank()
。考虑<代码> df>代码>在您将其放入ggTrp之前是您的代码> df<代码>。< /p>
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")

只要您的列名保持不变,这应该可以工作

编辑:

要重新排序
call\u 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"])]))

谢谢你的回答和解释!你能帮我回答以下问题吗?1) 添加虚拟类别的原因是什么?2) 如何按性能变量的降序对所有调用原因进行排序?虚拟数据需要
call\u reason
变量的值,以便它在x轴上有一个位置(翻转后的y轴)。这是必需的,因为您已将此变量映射到x轴,否则将找不到x轴值。我将发布重新排列调用原因的代码,作为对我答案的编辑。