How to plot dates as dates (not numbers or character) on x axis of ggplot?

醉酒当歌 提交于 2019-12-13 04:35:05

问题


I have a huge data set containing bacteria samples (4 types of bacteria) from 10 water resources from 2010 until 2019. some values are missing so we need to not include them in the plot or analysis.

I want to plot a time series for each type of bacteria for each resource for all years. What is the best way to do that?

library("ggplot2")
BactData= read.csv('Råvannsdata_Bergen_2010_2018a.csv', sep='\t',header=TRUE)
summary(BactData,na.rm = TRUE)
df$Date = as.Date( df$Date, '%d/%m/%Y')
#require(ggplot2)
ggplot( data = df, aes( Date,BactData$Svartediket_CB )) + geom_line() 
#plot(BactData$Svartediket_CB,col='brown')
plot(BactData$Svartediket_CP,col='cyan')
plot(BactData$Svartediket_EC,col='magenta')
plot(BactData$Svartediket_IE,col='darkviolet')

using plot is not satisfactory because the x axis is just numbers not dates . Tried to use ggplot but got an error message. I am beginner in R.

Error message

Error in df$Date : object of type 'closure' is not subsettable

Data as CVS file with tab delimiter


回答1:


This will do the trick

BactData = read.csv('Råvannsdata_Bergen_2010_2018a.csv', sep='\t',header=TRUE, stringsAsFactors = F)

colnames(BactData)[1] <- "Date"

library(lubridate)
BactData$Date = dmy(BactData$Date) # converts strings to date class 
ggplot(data = BactData, aes(Date, Svartediket_CB )) + geom_line()

You can filter for any year using dplyr with lubridate. For example, 2017:

library(dplyr)
BactData %>% filter(year(Date) == 2017) %>% 
  ggplot(aes(Date, Svartediket_CB )) + geom_line()

Or for two years

library(dplyr)
BactData %>% filter(year(Date) == 2017 | year(Date) == 2018) %>% 
  ggplot(aes(Date, Svartediket_CB )) + geom_line()


来源:https://stackoverflow.com/questions/59008219/how-to-plot-dates-as-dates-not-numbers-or-character-on-x-axis-of-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!