Y label overlapping ggplot and ordering

Viewed 82

I have two problems at the moment which I can't seem to be able to fix

1.My ggplot y axis label is overlapping since I introduced ranking to order the values

2.I would like to have the order of the countries as I have ordered the datac("US","GB", "CN", "FR", "JP") but facet_wrap method seems to reorder them.

1 Answers

The second issue could be easily solved by setting (!!) the factor levels using e.g. mutate.

Concerning the first issue. From the image of your dataset ...

I would guess that your data is grouped by country. Hence your ranks are duplicated and when setting the axis breaks and labels via scale_x_continuous you get a mess of duplicated labels.

To prevent this: Check your data, make sure that it is not grouped so that you get unique ranks.

A second approach to solve this issue would be to make use of tidytext::reorder_within and tidy text::scale_x_reordered as I do in my approach below:

Using some random example data try this:

library(ggplot2)
library(dplyr)
library(hrbrthemes)
library(tidytext)

# Random example data
set.seed(42)

datos2 <- data.frame(
  customer_country = rep(c("US","GB", "CN", "FR", "JP"), each = 10),
  category = rep(LETTERS[1:10], 5),
  sum_amount = runif(5 * 10)
)

detail <- subset(datos2, customer_country %in% c("US","GB", "CN", "FR", "JP"))
detail <- detail %>% 
  mutate(customer_country = factor(customer_country, levels = c("US","GB", "CN", "FR", "JP")),
         rank = tidytext::reorder_within(category, sum_amount, customer_country))


ggplot(detail) +
  geom_segment( aes(x=rank, xend=rank, y=0, yend=sum_amount), color="black") +
  geom_point( aes(x=rank, y=sum_amount, color=customer_country)) +
  coord_flip()+
  theme_ipsum() +
  theme(
    legend.position = "none",
    panel.border = element_blank(),
    panel.spacing = unit(0.1, "lines"),
    strip.text.x = element_text(size = 8)
    , element_line(size = 11)
  ) +
  xlab("") +
  ylab("Value of Y") +
  facet_wrap(~customer_country, ncol=1, scale="free") +
  tidytext::scale_x_reordered()

Related