Reputation: 10112
I have a ggplot2
plot where the x axis variable is a factor, but represents different time spans in months and years (1m, 3m, 6m, 1y, 2y, 3y, 5y, 7y, 10y, 20y, and 30y -- this is a yield curve). The factor variable gives me nice labels, but even spacing. I would like the x axis spacing proportional to the time span.
I think this adjustment should come through scale_x_discrete()
, but I only see an expand
option. Is my only option to convert my factors to continuous variables and forego the pretty factor labels?
Here's the relevant code.
plotYieldCurve <- ggplot(data=yieldCurveSub, aes(x=variable, y=value, group=Date))
plotYieldCurve <- plotYieldCurve + geom_line(aes(linetype=factor(Date)))
plotYieldCurve <- plotYieldCurve + xlab("Maturity")
plotYieldCurve <- plotYieldCurve + ylab("YTM")
plotYieldCurve <- plotYieldCurve + labs(linetype="Date")
plotYieldCurve
The dput
on yieldCurveSub
is as follows.
> dput(yieldCurveSub)
structure(list(Date = structure(c(14746, 16209, 16574, 14746,
16209, 16574, 14746, 16209, 16574, 14746, 16209, 16574, 14746,
16209, 16574, 14746, 16209, 16574, 14746, 16209, 16574, 14746,
16209, 16574, 14746, 16209, 16574, 14746, 16209, 16574, 14746,
16209, 16574), class = "Date"), variable = structure(c(1L, 1L,
1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L, 6L, 6L, 6L,
7L, 7L, 7L, 8L, 8L, 8L, 9L, 9L, 9L, 10L, 10L, 10L, 11L, 11L,
11L), .Label = c("1 mo", "3 mo", "6 mo", "1 yr", "2 yr", "3 yr",
"5 yr", "7 yr", "10 yr", "20 yr", "30 yr"), class = "factor"),
value = c(0.16, 0.01, 0.02, 0.16, 0.03, 0.02, 0.23, 0.05,
0.07, 0.36, 0.09, 0.23, 0.81, 0.36, 0.63, 1.3, 0.79, 1.01,
2.2, 1.56, 1.6, 2.9, 2.09, 2.01, 3.47, 2.54, 2.27, 4.17,
3.11, 2.79, 4.35, 3.39, 3.05)), row.names = c(NA, -33L), .Names = c("Date",
"variable", "value"), class = "data.frame")
Upvotes: 2
Views: 2525
Reputation: 16099
Would treating them as numeric be acceptable?
yieldCurveSub$variable <- ifelse(grepl("mo", yieldCurveSub$variable),
as.numeric(as.character(gsub("[^0-9]", "", yieldCurveSub$variable))) / 12,
as.numeric(as.character(gsub("[^0-9]", "", yieldCurveSub$variable))))
ggplot(yieldCurveSub) +
geom_point(aes(x = variable, y = value)) +
scale_x_continuous(breaks = c(1/12, 3/12, 6/12, 1, 2, 3, 5, 7, 10,20, 30),
labels = c("1 mo", "3 mo", "6 mo", "1 yr", "2 yr", "3 yr", "5 yr", "7 yr",
"10 yr", "20 yr", "30 yr")
Upvotes: 3