ggplot:重新排序多面(棒棒糖)图

时间:2019-07-20 19:12:05

标签: r ggplot2

我正在尝试制作一个多面的棒棒糖图,以显示特定日志(x)在四个特定组(grp)中发生的频率。

我可以生成多面图,但是我想按日志发生的次数(val)对每个方面(即grp)进行排序。

我尝试调整因子水平和标签,我无法对图表进行重新排序,以使每个grp都按val的降序排列。

ggplot(total) +
  geom_segment( aes(x=x, xend=x, y=0, yend=val), color="grey") +
  geom_point( aes(x=x, y=val, color=grp), size=3 ) +
  coord_flip()+
  facet_wrap(~grp, ncol=1, scale="free_y")

这是我的数据帧的dput输出

structure(list(x = c("LANCET", "QUARTERLY JOURNAL OF ECONOMICS", 
"WORLD DEVELOPMENT", "JOURNAL OF DEVELOPMENT ECONOMICS", "WORLD BANK ECONOMIC REVIEW", 
"WORLD BANK RESEARCH OBSERVER", "JOURNAL OF DEVELOPMENT ECONOMICS", 
"PLOS ONE", "WORLD BANK ECONOMIC REVIEW", "WORLD DEVELOPMENT", 
"LANCET", "AMERICAN ECONOMIC REVIEW", "AGRICULTURAL ECONOMICS", 
"AIDS", "CLIMATIC CHANGE", "ECONOMICS LETTERS", "HEALTH POLICY", 
"HUMAN RESOURCES FOR HEALTH", "JOURNAL OF DEVELOPMENT STUDIES", 
"JOURNAL OF AFRICAN ECONOMIES", "APPLIED ECONOMICS LETTERS", 
"REVIEW OF FAITH & INTERNATIONAL AFFAIRS", "JOURNAL OF INTERNATIONAL DEVELOPMENT", 
"WORLD DEVELOPMENT"), val = c(19L, 15L, 13L, 11L, 8L, 6L, 6L, 
6L, 5L, 5L, 4L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 9L, 7L, 6L, 6L, 5L, 
5L), grp = c("4", "4", "4", "4", "4", "4", "3", "3", "3", "3", 
"3", "3", "2", "2", "2", "2", "2", "2", "1", "1", "1", "1", "1", 
"1")), row.names = c(NA, -24L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

ggplot2中没有内置方法可以执行您想要的操作。但是有一种解决方法,您可以转换数据框并创建新的列以进行排序。

library(dplyr)
library(ggplot)
# ascending by val
plot_data <- total %>%
    arrange(grp,val) %>% # sort data based on group and value
    mutate(rank = row_number()) # this will be used as x axis

# descending by val
plot_data <- total %>%
    arrange(grp,val) %>%
    mutate(rank = nrow(total) - row_number() + 1)

plot_data %>%
    ggplot() +
    geom_segment( aes(x=rank, xend=rank, y=0, yend=val), color="grey") +
    geom_point( aes(x=rank, y=val, color=grp), size=3 ) +
    coord_flip()+
    facet_wrap(~grp, ncol=1, scale="free_y") +
    scale_x_continuous(
        breaks = plot_data$rank, # specify tick breaks using rank column
        labels = plot_data$x # specify tick labels using x column
    )

升序

enter image description here

下降

enter image description here

您也可以阅读此博客文章,以获取更深入的解释:

https://drsimonj.svbtle.com/ordering-categories-within-ggplot2-facets