【发布时间】:2019-05-29 00:14:10
【问题描述】:
我使用 facet_grid 来为 x 轴设置两个标签。
我的数据如下所示:
library(dplyr)
library(tidyverse)
library(ggplot2)
set.seed(22)
df <- c(1:1260)
df <- as_tibble(c(1:1260))
colnames(df)[1] <- "price"
df$price[1] <- 100
for (i in seq(2,1260)){df$price[i]<- df$price[i-1]*0.8 + rlnorm(1, 2, 2)}
df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
"Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)
df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)
用户 M-M 使用此代码:
df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
"Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)
df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)
#solution:
month_lab <- rep(unique(df$month), length(unique(df$year)))
year_lab <- unique(df$year)
df %>%
as.data.frame() %>%
rename(price = 1) %>%
mutate(rnames = rownames(.)) %>%
ggplot(aes(x = as.numeric(rnames), y = price,
group = year)) +
geom_line() +
labs(title = "Stock Price Chart", y = "Price", x = "date") +
scale_x_continuous(breaks = seq(1, 1260, by = 21),
labels = month_lab, expand = c(0,0)) +
facet_grid(~year, space="free_x", scales="free_x", switch="x") +
theme(strip.placement = "outside",
strip.background = element_rect(fill=NA,colour="grey50"),
panel.spacing=unit(0,"cm"))
我几乎得到了我所追求的东西,除了图中标记的年份之间的跳跃:
有没有办法让线路连续?
【问题讨论】:
-
数据生成出错。可以查一下吗?
-
@RonakShah 改变了它。现在可以用了吗?
标签: r ggplot2 time-series