如何在ggplot的x轴上将日期绘制为日期(而不是数字或字符)? [英] How to plot dates as dates (not numbers or character) on x axis of ggplot?
问题描述
我有一个庞大的数据集,其中包含从2010年到2019年的10种水资源的细菌样本(4种细菌)。某些值缺失了,因此我们无需在图表或分析中将它们包括在内。
$ b
我想绘制所有年份每种资源的每种细菌的时间序列。
最好的方法是什么?
library( ggplot2)
BactData = read .csv('Råvannsdata_Bergen_2010_2018a.csv',sep ='\t',header = TRUE)
摘要(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')
图(BactData $ Svartediket_CP,col ='cyan')
图(BactData $ Svartediket_EC,col ='magenta')
图(BactData $ Svartediket_IE,col ='darkviolet')
使用图并不令人满意,因为x轴只是数字而不是日期。尝试使用ggplot,但收到错误消息。我是R语言的初学者。
错误消息
df错误$ Date:类型为'closure'的对象不可子集化
您可以使用过滤任何年份 dplyr
和 lubridate
。例如,2017年:
library(dplyr)
BactData%&%;%filter(year(Date)== 2017)%>%
ggplot(aes(Date,Svartediket_CB))+ geom_line()
或两年
library(dplyr)
BactData%&%;%过滤器(year(Date)== 2017 | year(Date)== 2018)%>%
ggplot(aes(日期,Svartediket_CB))+ geom_line()
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
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()
这篇关于如何在ggplot的x轴上将日期绘制为日期(而不是数字或字符)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!