Reputation: 13
I am trying to produce a faceted lollipop graph that shows how often a particular journal (x) occurs for four particular groups (grp).
I can produce the faceted graph, but I want to order each facet (i.e. grp) by the number of times the journal occurs (val).
I have tried adjusting the factor levels and labels, I am unable to reorder the graph so that each grp is in descending order of 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")
here is the dput output for my dataframe
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")
Upvotes: 1
Views: 1952
Reputation: 6106
There is no built-in way in ggplot2 to do to what you want. But there is a workaround that you can transform the data frame and create new columns for ordering.
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
)
Ascending
Descending
You can also read this blogpost for the explanation in more depth:
https://drsimonj.svbtle.com/ordering-categories-within-ggplot2-facets
Upvotes: 2