代码之家  ›  专栏  ›  技术社区  ›  Tito Sanz

如何在facet_网格内的ggplot2中显示更高的值

  •  0
  • Tito Sanz  · 技术社区  · 7 年前

    我刚刚在ggplot2中找到了函数facet\u grid,它太棒了。问题是:我有一个名单,上面有6个国家(HC列)和世界各地航班的目的地。我的数据如下所示:

               HC Reason Destination  freq       Perc
            <chr>  <chr>       <chr> <int>      <dbl>
     1    Germany  Study     Germany     9  0.3651116
     2    Germany   Work     Germany     3  0.1488095
     3    Germany Others     Germany     3  0.4901961
     4    Hungary  Study     Germany   105 21.4285714
     5    Hungary   Work     Germany   118 17.6382661
     6    Hungary Others     Germany    24  5.0955414
     7 Luxembourg  Study     Germany   362 31.5056571
    

    Geograp %>% 
      gather(key=Destination, value=freq, -Reason, -Qcountry) %>%
      rename(HC = Qcountry) %>%
      group_by(HC,Reason) %>%
      mutate(Perc=freq*100/sum(freq)) %>%
      ggplot(aes(x=Perc, y=reorder(Destination,Perc))) +
      geom_point(size=3) +
      theme_bw() +
      facet_grid(HC~Reason) +
      theme(panel.grid.major.x = element_blank(),
            panel.grid.minor.x = element_blank(),
            panel.grid.major.y = element_line(colour = "grey60", linetype = "dashed"))
    

    enter image description here 我想避免在y轴上过度绘制。提前感谢!!!

    2 回复  |  直到 7 年前
        1
  •  2
  •   Richard    7 年前

    您可以创建一个变量,指示每个目的地按国家/地区的排名,然后在ggplot调用中选择排名为<=10,例如。

    ggplot(data = mydata[rank <= 10, ], ....)
    

    PS:目前,您可以使用管道在一行中创建数据和打印数据。我将分离数据创建和绘图步骤。

        2
  •  0
  •   Mal_a    7 年前

    由于您没有以正确的格式发布数据(请签出 dput() ),我只使用了一个样本数据。使用 dplyr 包i在本例中按grp变量分组( group_by(grp) ,在您的情况下 )并选择了前10行( ...top_n(n = 10,... )按x变量排序( wt = x ,在您的情况下 频率

    library(dplyr)
    set.seed(123)
    d <- data.frame(x   = runif(90),grp = gl(3, 30))
    
    d %>%
    group_by(grp) %>%
    top_n(n = 10, wt = x) %>%
    ggplot(aes(x=x, y=grp)) + geom_point()