我制作了一条包含两条线的线图,其中x轴为日期。如下图所示,使用此处的代码:
date_col <- paste0("2018-01-0", 1:9)
col1 <- runif(9)
col2 <- runif(9)
df <- as.data.frame( cbind(date_col, col1, col2) )
df$date_col <- as.Date(df$date_col)
colnames(df) <- c("Date" , "Col1", "Col2")
df$Col1 <- as.numeric(as.vector(df$Col1))
df$Col2 <- as.numeric(as.vector(df$Col2))
axis_size = 10
legend_size = 10
title_size = 12
line_size = 1
caption_size=10
meltdta <- melt(df, id = "Date")
plotobj <- ggplot(meltdta, aes(x=Date, y=value, color=variable) )+
geom_line(size=line_size)+ylab("Level") + theme_bw() +
ggtitle("trial") +
theme(axis.title=element_text(size=axis_size),
legend.position = "bottom")
print(plotobj)
我现在想将x轴上的日期标签更改为Q0,Q1,Q2 ...到Q8。我不知道该怎么办?我尝试过:
plotobj + scale_x_discrete(labels=paste0("Q", 0:8) )
在打印对象之前,但是它似乎不起作用。
我也尝试添加此行:
df[, "Date"] <- paste0("Q", 0:8)
在行之前
df$Col1 <- as.numeric(as.vector(df$Col1))
但是它产生了一个空图,如下所示,错误:geom_path:每个组仅包含一个观察值。您是否需要调整小组审美?
答案 0 :(得分:0)
您非常亲密。 scale_x_discrete
不起作用,因为数据不是离散的(它是日期)。
您可以在scale_x_date
中强制使用特定标签:
plotobj+
scale_x_date(breaks = seq(as.Date("2018-01-01"),
as.Date("2018-01-09"),
by = "1 day"),
labels = paste0("Q", 0:8))