[英]How to tell R's ggplot2 to put tick marks for some values of x-axis and still keep vertical lines for other values
我正在使用R中的ggplot2創建一個時間序列。我想知道如何在標記的月份(例如Mar 07,Mar 08等)中顯示x軸上的刻度線,同時保持垂直灰線為每個月。
主要原因是因為每個月都有一個刻度標記,因此很難知道哪一個與標簽相對應。
這是一個情節的例子:
這是后面的R線:
ggplot(timeseries_plot_data_mean,aes(as.numeric(project_date)))+
geom_line(aes(y=num_views))+geom_point(aes(y=num_views))+
stat_smooth(aes(y=num_views),method="lm")+
scale_x_continuous(breaks = xscale$breaks, labels = xscale$labels)+
opts(title="Monthly average num views")+xlab("months")+ylab("num views")
這是想要產生的。 查看刻度線如何定位在月份標簽的正上方,垂直線仍然顯示每個月。
我使用Inkscape手動編輯上面的圖,(忽略q,Inkscape奇怪地取代了q的點)
以下是使用scale_x_date()
的minor_breaks
參數的解決方案。 要使用它,您的x值必須是Date
類而不是numeric
。
library(ggplot2)
set.seed(123)
x <- seq(as.Date("2007/3/1"), as.Date("2012/4/1"), by = "1 month")
y <- ((exp(-10 * seq(from=0, to=1, length.out=length(x))) * 120) +
runif(length(x), min=-10, max=10))
dat <- data.frame(Months=x, Views=y)
x_breaks <- seq(as.Date("2007/3/1"), as.Date("2012/4/1"), by="1 year")
x_labels <- as.character(x_breaks, format="%h-%y")
plot_1 <- ggplot(dat, aes(x=Months, y=Views)) +
theme_bw() +
geom_line() +
geom_point() +
scale_x_date(breaks=x_breaks, labels=x_labels, minor_breaks=dat$Months)
png("plot_1.png", width=600, height=240)
print(plot_1)
dev.off()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.