我有以下数据(类:data.frame):
Date S D
199011 1.023247 1.009845
199012 1.050828 1.015818
199101 1.066754 1.023077
199102 1.147112 1.033462
199103 1.160859 1.042610
199104 1.164412 1.049691
199105 1.204586 1.058778
199106 1.173015 1.063795
199107 1.220449 1.074115
199108 1.210946 1.075537
199109 1.219717 1.076117
199110 1.256516 1.080941
199111 1.220505 1.087333
199112 1.288720 1.100406
199201 1.306862 1.106454
199202 1.304459 1.108409
199203 1.255841 1.111392
199204 1.243667 1.113684
199205 1.286353 1.126754
199206 1.262842 1.131144
199207 1.283566 1.138307
199208 1.255925 1.144240
199209 1.258397 1.149799
199210 1.243018 1.159166
199211 1.257497 1.165859
199212 1.284947 1.173460
199301 1.294014 1.180281
199302 1.313828 1.190518
199303 1.386941 1.202399
199304 1.428233 1.215996
和以下代码:
library(tidyverse);
data2 %>%
gather(what, value, S:D) %>%
ggplot(aes(as.factor(Date), value, colour = what,group = what)) +
geom_line(size=0.8)+
labs(x = "Date", y = "Return", title = " Survivorshipbias", color="Legend") + scale_colour_discrete(labels = c("Actual","Simulation"))+ scale_x_discrete(breaks =c(0,1,2), labels=as.character(c("1990","2000","2010"))) + theme_gray() + theme(plot.title = element_text(hjust = 0.5))
我希望能够将年份(1990年,2000年,2010年)手动设置为x轴值。我试过了
scale_x_continuous
但没有运气,因为它返回一个错误,说它是一个离散变量。我已经能够生成图表,我可以手动插入/说明x轴值,但由于某种原因,它目前无法正常工作。我见过这个question,但我的情况没有运气。
另外,有谁知道为什么垂直线消失了?也许这两件事是相关的?
提前谢谢你,周末愉快。
答案 0 :(得分:2)
以下是使用scale_x_date
格式化的方法:
dat %>%
mutate(Date = as.Date(paste0(Date, "01"), format ="%Y%m%d")) %>%
gather(key, val, 2:3) %>%
ggplot(aes(Date, val, colour = key, group = key)) +
geom_line(size=0.8)+
labs(x = "Date", y = "Return", title = " Survivorshipbias", color="Legend")+
scale_colour_discrete(labels = c("Actual","Simulation"))+
scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
theme_gray() +
theme(plot.title = element_text(hjust = 0.5))
数据:
structure(list(Date = c(199011L, 199012L, 199101L, 199102L, 199103L,
199104L, 199105L, 199106L, 199107L, 199108L, 199109L, 199110L,
199111L, 199112L, 199201L, 199202L, 199203L, 199204L, 199205L,
199206L, 199207L, 199208L, 199209L, 199210L, 199211L, 199212L,
199301L, 199302L, 199303L, 199304L), S = c(1.023247, 1.050828,
1.066754, 1.147112, 1.160859, 1.164412, 1.204586, 1.173015, 1.220449,
1.210946, 1.219717, 1.256516, 1.220505, 1.28872, 1.306862, 1.304459,
1.255841, 1.243667, 1.286353, 1.262842, 1.283566, 1.255925, 1.258397,
1.243018, 1.257497, 1.284947, 1.294014, 1.313828, 1.386941, 1.428233
), D = c(1.009845, 1.015818, 1.023077, 1.033462, 1.04261, 1.049691,
1.058778, 1.063795, 1.074115, 1.075537, 1.076117, 1.080941, 1.087333,
1.100406, 1.106454, 1.108409, 1.111392, 1.113684, 1.126754, 1.131144,
1.138307, 1.14424, 1.149799, 1.159166, 1.165859, 1.17346, 1.180281,
1.190518, 1.202399, 1.215996)), .Names = c("Date", "S", "D"), class = "data.frame", row.names = c(NA,
-30L))