rdataframeggplot2

horizontally match two ggplots in R


I have two plots in R.g1 and g2.

library(dplyr)
library(ggplot2)
library(forcats)
set.seed(123)  # Setting seed for reproducibility
levels_country  = c('USA', 'UK', 'FRANCE', 'GERMANY')
country = sample(levels_country, 50, replace = TRUE)
levels_smoke = c('smoke', 'not smoke', 'vaping')
smoke   = sample(levels_smoke, 50, replace = TRUE)
df = tibble(country,smoke) %>%
  mutate(
    country = factor(country, levels = levels_country),
    smoke = factor(smoke, levels = levels_smoke)
  )
g1 = mutate(df, id=row_number()) |>
  pivot_longer(-c(id,  country), names_to="group") |>
  pivot_wider(names_from= country) |>
  ggstats::gglikert(c(unique(df$country)), 
           facet_rows=vars(group))





df2 <- df %>%
  mutate(smoking_status = ifelse(smoke %in% c("smoke", "vaping"), "smoking", "not smoking"))

# Count how many are 'smoking' in each country
df_counts <- df2 %>%
  filter(smoking_status == "smoking") %>%
  count(country)

# Plotting
g2 = ggplot(df_counts, aes(x = country, y = n, fill = country)) +
  geom_bar(stat = "identity") +
  labs(
    title = "Count of Smoking Individuals by Country",
    x = "Country",
    y = "Count of Smokers"
  ) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1),
    plot.title = element_text(hjust = 0.5)
  ) +
  coord_flip()+
  guides(fill = "none")  # Remove legend for fill


ggpubr::ggarrange(g1,g2)

resulting to :

I want the g1 left smoke plot to be sorted with smoke and vaping in a descending order.

For example in USA, the sum of smoke and vaping will be 75% and not smoke 25%. In UK, the sum of smoke and vaping will be 70% and not smoke 30%.

USA must be at the bottom and UK above USA. (sample data due to simulation might give different results).

The two plots to have horizontally the same country.Both bars in the same height to be the same country.

How can I match horizontally the two panels to be in the same height as the g1 as reference.Also I want the two legends to be displayed on bottom of these two plots.

enter image description here


Solution

  • Patchwork is good at aligning plots:

    library(patchwork)
    g1 + g2
    

    To order the bars in g2 as they are in g1, set the factor levels of the variable you mapped to the x aesthetic, country:

    df_counts$country <- factor(df_counts$country, levels = c("GERMANY", "USA", "UK", "FRANCE"))