![](/img/trans.png)
[英]Error in customizing the x axis with scale_x_discrete() in ggplot2
[英]Manually scale discrete x axis variable in ggplot2
我有一個ggplot2
圖,其中x軸變量是一個因數,但代表月份和年份的不同時間跨度(1m,3m,6m,1y,2y,3y,5y,7y,10y,20y和30y-這是收益率曲線 )。 因子變量給我很好的標簽,但間距均勻。 我希望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")
將它們視為數字是否可以接受?
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.