'How to automatically make an axis with a gradation from 1 to max(n) when using facet_wrap ggplot2

I have a data.frame(tt) with 3 columns:

  1. nazvReki - grouping variable (18 values);
  2. rang - axis X (443 entries from 1 to 70. It takes values from 1 to 70, but for different grouping variables it is different, where 8, where 10, where 16...);
  3. procent - axis Y (0-100 %).

I'm drawing a picture:

ggplot(tt) +
  geom_line(aes(rang, procent)) +
  scale_x_continuous(
    name = c("Rang"),
    breaks = scales::pretty_breaks(n = 10)
  ) +
  scale_y_continuous(name = c("Procent")) +
  facet_wrap( ~ nazvReki, nrow = 4, scales = "free_x") +
  theme_bw()

The result is not very: enter image description here

I need the values to start with 1, and that there are no vertical lines between the numbers.

I do it a little differently:

tt$rang <- factor(tt$rang)

ggplot(tt, aes(rang, procent)) +
  geom_line(aes(group = nazvReki)) +
  scale_x_discrete(name = c("Rang")) +
  scale_y_continuous(name = c("Procent")) +
  facet_wrap( ~ nazvReki, nrow = 4, scales = "free_x") +
  theme_bw()

It turns out better:

enter image description here

But not all the numbers fit. I play with the parameters, make several options, combine them in a graphic editor. The result is almost perfect

enter image description here

What is missing for perfection? So that on the X-axis the school always starts with 1 and ends with the maximum value, 5-8 values can be inserted between them. And it was all done automatically.

And the question is: can this be done in ggplot2?



Solution 1:[1]

Now, this will do half of the trick. It won't necessarily start at 1 instead of 0, but I would ask myself if it really has to do so. I don't know why or how to force a start at 1...

ggplot(tt) +
  geom_line(aes(rang, procent)) +
  scale_x_continuous(
    name = c("Rang"),
    breaks = scales::pretty_breaks(n = 10),
    limits = c(1,NA) #start will be at 1, but not the start of the scale
  ) +
  scale_y_continuous(name = c("Procent")) +
  facet_wrap( ~ nazvReki, nrow = 4, scales = "free_x") +
  theme_bw() + 
  theme(panel.grid.minor = element_line(color = NA)) #this will remove the secondary lines

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lucabiel