簡體   English   中英

如何告訴R的ggplot2為某些x軸值設置刻度線,並保持其他值的垂直線

[英]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軸上的刻度線,同時保持垂直灰線為每個月。

主要原因是因為每個月都有一個刻度標記,因此很難知道哪一個與標簽相對應。

這是一個情節的例子:

看看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,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()

plot_1.png

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM