Reputation: 23
Suppose I have data for the years 1913, 1928, 1929, ..., 1938, and I want to plot these years on an x-axis where each year is evenly spaced, i.e., same distance between 1913 and 1928 as between 1928 and 1929. How can I do this in ggplot?
Everything I have tried so far results in 1913 appearing significantly far to the left from 1928, as if ggplot is plotting my x-axis on a number line. Please see the attached link for an image of the x-axis I am trying to replicate.
Thank you for your help!
Data:
fig1dat <- structure(list(year = c(1913L, 1928L, 1929L, 1930L, 1931L, 1932L, 1933L, 1934L, 1935L, 1936L, 1937L, 1938L), coll = c(NA, 1.67638484, 3.717201166, 23.54227405, 52.98833819, 61.88046647, NA, NA, 83.60058309, NA, NA, 93.65889213), grain = c(78.93586006, 63.19241983, 62.09912536, 65.08746356, 56.19533528, 56.19533528, 65.08746356, 68.29446064, 75.14577259, 56.04956268, 97.44897959, 74.12536443)), class = "data.frame", row.names = c(NA, -12L))
Code:
fig1 <- reshape::melt(fig1dat, id.var='year')
p <- ggplot(fig1, aes(x=year, y=value, col=variable)) +
scale_y_continuous(name = "Livestock (millions)",
breaks = seq(0, 100, by=25), expand = c(0, 0), limits = c(0,100)) +
scale_x_continuous(name = "",
breaks = c(1913, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938), expand = c(0, 0), limits = c(1912.5,1938.5)) +
geom_line(size = 0.7) +
geom_point() +
theme_bw()
I am new at using stack for R, so apologies for any errors in the post.
Upvotes: 2
Views: 1063
Reputation: 389235
One option would be to turn the year
variable to factor
.
library(ggplot2)
fig1 <- reshape::melt(fig1dat, id.var='year')
fig1$year <- factor(fig1$year)
p <- ggplot(fig1, aes(x=year, y=value, col=variable, group = variable)) +
scale_y_continuous(name = "Livestock (millions)",
breaks = seq(0, 100, by=25),
expand = c(0, 0), limits = c(0,100)) +
geom_line(size = 0.7) +
geom_point() +
theme_bw()
p
Upvotes: 3