在ggplot2中手动缩放离散x轴变量

时间:2015-05-20 11:09:34

标签: r ggplot2 axis-labels

我有一个ggplot2图,其中x轴变量是一个因子,但代表不同的时间跨度,以月和年为单位(1m,3m,6m,1y,2y,3y,5y,7y,10y,20y和30y - 这是yield curve)。因子变量给了我很好的标签,但是间距都很均匀。我希望x轴间距与时间跨度成比例。

我认为此调整应通过scale_x_discrete(),但我只看到expand选项。我唯一的选择是将我的因子转换为连续变量并放弃漂亮因子标签吗?

以下是相关代码。

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

dput上的yieldCurveSub如下所示。

> 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")

1 个答案:

答案 0 :(得分:2)

将它们视为数字是否可以接受?

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")