X-axis does not show all values of a numeric variable; X-axis does not have equal distancing between values

Dear R-experts,

I have the following dataset “df” (I couldn’t find an option to upload it here, otherwise I would surely do it).

1907-1

My plot is:

plot <- ggplot(data=df, aes(x=date, y = urban, colour = inst)) + geom_point(aes(x=date, 
                           y = mean_figure6, colour=as.factor(inst)), size=6) +
  geom_line(aes(x=date, 
                y = mean_figure6, colour=as.factor(inst)), size=2) + 
  geom_smooth(se = FALSE, method = lm, linetype="dashed")

I am currently struggling on two (silly) difficulties:

First, I want X-axis to display all values of "date" (it does not show 1300, 1500, 1700, 1750 and 1850 on the plot above);
Second, on the X-axis the difference between 1000 and 1200 is wider than it is between 1200 and 1300, or between 1700 and 1750 (because "date" is numeric). I want X-axis to have equal distance between all 10 values of "date".
I have found one suggestion in the Internet about doing it, which unfortunately did not work:

scale_x_continuous("date", labels = as.character(date), breaks = date)

Guys, could you please help me out?

Change "date" to be a factor

Also tried.
In that case, neither geom_line or geom_smooth works

the warning geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic? gives a clue to how to address your issue.
you simply add group=1, I simplified your plot code also, see

library(tidyverse)
set.seed(42)
(df <- data.frame(
  date=100*c(10,12:17,17.5,18,18.5),
  inst="West"
) |> mutate(urban=rnorm(10)+date/1000,
  mean_figure6=rnorm(10)+(date^2-100*date)/1000))

plot <- ggplot(data=df, aes(x=date, y = urban, colour = inst)) + 
  aes(y = mean_figure6) + 
  geom_point(size=6) +
  geom_line(size=2) + 
  geom_smooth(se = FALSE, method = lm, linetype="dashed")
plot


(df2 <- df |> mutate(date=as_factor(date)))

plot2 <- ggplot(data=df2, aes(x=date, y = urban, colour = inst)) + 
  aes(y = mean_figure6,group=1) + 
  geom_point(size=6) +
  geom_line(size=2) + 
  geom_smooth(se = FALSE, method = lm, linetype="dashed")
plot2

Thank you for your quick and detailed answers!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.