Converting Continuous Dates to Discrete X-Axis Values in ggplot2 R Plot
The issue here is that the scale_x_discrete
function in ggplot2 requires discrete values for x-axis. However, seq_range(1920:1950)
generates a continuous sequence of dates.
To solve this problem, we can use seq_along()
to get the unique indices of each date and then map those indices back to their corresponding dates using the map
function from the tidyr package.
Here is how you can do it:
library(ggplot2)
library(tidyr)
df$x <- seq_range(1920:1950, dim(df)[1])
df$y <- y
df$idx <- seq_along(df$x)
ggplot(df, aes(x = idx, y = y)) + geom_line() + scale_x_discrete(breaks = df$x)
In this code:
seq_range(1920:1950, dim(df)[1])
generates the sequence of dates.seq_along(df$x)
gets the indices of each date in the dataframe.- We then map these indices back to their corresponding dates by using
map
function from tidyr package. - Finally, we plot the line chart with the x-axis values as the unique dates and y-axis values are already present in the dataframe.
Last modified on 2024-04-08