简体   繁体   English

R ggplot2 - 在同一图中绘制年份变量

[英]R ggplot2 - Plot year variable one over the other in same plot

How do I plot each year as a separate line in ggplot2 I tried the below code but it seems to plot continuous as a single plot.如何在 ggplot2 中将每年绘制为单独的线我尝试了以下代码,但它似乎将连续绘制为单个图。

library(ggplot2)

# Dummy data
data <- data.frame(
  Date = c(as.Date("2017-01-14") - 0:13,as.Date("2016-01-14") - 0:13),
  value = runif(28) 
)
#data$Date <- strptime(data$Date, "%Y-%m-%d" )
data$Year <- as.character(year(data$Date))
data$Year <- factor(data$Year)

ggplot(data) + geom_line(aes(x = Date, y = value, group=Year, color=Year)) +
  scale_x_date(date_breaks = "1 day", date_labels = "%d-%m-%y") +
  theme(axis.text.x = element_text(angle = 90))

在此处输入图片说明 But I want each year to be a separate graph in the same plot.但我希望每一年都在同一个情节中成为一个单独的图表。

something like below像下面这样的东西

在此处输入图片说明

Try this approach formating day and month in your date.试试这种方法在你的日期中格式化日期和月份。 You got a mess in your plot because of the different year in your date variable.由于日期变量中的年份不同,您的情节一团糟。 Setting format can help you.设置格式可以帮助您。 Here the code:这里的代码:

library(ggplot2)
library(lubridate)
# Dummy data
data <- data.frame(
  Date = c(as.Date("2017-01-14") - 0:13,as.Date("2016-01-14") - 0:13),
  value = runif(28) 
)
data$Year <- as.character(year(data$Date))
data$Year <- factor(data$Year)
#Format month
data$MonthDay <- format(data$Date,'%b-%d')
#Plot
ggplot(data) + geom_line(aes(x = MonthDay, y = value, group=Year, color=Year)) +
  theme_bw()+
  theme(axis.text.x = element_text(angle = 90))

Output:输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM