Fixing the Order of Facets in Ggplot

Fixing the order of facets in ggplot

Make your size a factor in your dataframe by:

temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))

Then change the facet_grid(.~size) to facet_grid(.~size_f)

Then plot:
Sample Image

The graphs are now in the correct order.

R Changing Order of Facets

dfx$group <- factor(dfx$group, levels = c("SLG","BA"))

How to change the order of ggplot2 facets

reorder the factors

pd.long$Site <- factor(pd.long$Site,levels=c("KOA","KOB","KOO","EB","PNS","BED","KB","KER","KAU","KAD","RO","BEU"))

or more general answer where the order is based on the first apperance in the Site column :

pd.long$Site <- factor(pd.long$Site,levels=unique(pd.long$Site))

Change panel background color of specific ggplot facets

Perhaps you prefer a solution like this, no grob manipulation necessary:

ggplot(test) +
geom_rect(
aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf),
data.frame(rows = 'C', cols = 'A'),
fill = 'red', alpha = 0.5
) +
geom_point(aes(x = x, y = y)) +
facet_grid(vars(rows), vars(cols)) +
theme_minimal() +
theme(
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
panel.background = element_rect(fill = NA, color = "grey60")
)

Sample Image

A downside is that the color is drawn on top of the grid lines. Some transparency as used above is usually a good solution. Alternatively, you can use theme(panel.ontop = TRUE) to draw the grid lines on top, but then they will also be plotted on top of the data.

Reorder facets in ggplot when there are duplicate values

You can use fct_relevel, but ungroup the dataframe first.

library(forcats)
library(ggplot2)
library(dplyr)

groups %>%
ungroup() %>%
mutate(message = fct_relevel(message, "Personal", "General"),
maskalthalf = fct_relevel(maskalthalf, "Low", "High")) %>%
ggplot(aes(x = message, y = mean)) +
geom_col(width = 0.5, fill = "003900") +
geom_text(aes(label = round(mean, digits = 1), vjust = -2)) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = .2, position = position_dodge(.9)) +
labs(title = "Evaluations of Personal and General Convincingness",
y = "Rating",
x = "Personal evaluation or general evaluation") +
ylim(0, 8) +
facet_wrap(~maskalthalf)

Sample Image



Related Topics



Leave a reply



Submit