我有一张要在R中制作的图表,我遇到的第一个问题是我的日期格式不正确,它们的格式设置为因素,这导致它们在X轴上以随机顺序绘制(显然我希望它们按时间顺序排列(时间序列)。 理想情况下,我还希望只能每3个月显示一次,并以%B%y格式或2007年5月将其显示为“月”。添加...
感谢堆 安娜(新手)
以下是我正在使用的代码,但是日期在X轴上的时间顺序不正确,这是一个大问题...
> # ggplot2 library
library(ggplot2)
# The easiest way to get tidyr is to install the whole tidyverse:
library(tidyverse)
install.packages("tidyverse")
#load data or read data file, first set your working directory as the file that has your data files inside of it, to do this go to Session> Set working directory and pick the file
read.csv(file="Top25/RA_PH_0m_top25.csv", header=TRUE)
#next create a variable to read.csv the file in question
read_data1 <- read.csv(file="Top25/RA_PH_0m_top25.csv", header=TRUE)
#the easiest way to gather data is the following, gathering columns 2-9
gather(read_data1, zOTU, RA, 2:9, na.rm = FALSE, convert = FALSE)
gather_data1 <- gather(read_data1, zOTU, RA, 2:9, na.rm = FALSE, convert = FALSE)
#now you can graph the new gather_data1 in a stacked area plot
p <- ggplot(gather_data1, aes(x = Date, y = RA, group = zOTU, fill = zOTU)) +
geom_area(position="fill", color = "black")
#p <- p + scale_fill_manual(values = c("#999999", "#E69F00", "#999999", "#E69F00", "#999999", "#E69F00",
# "#999999", "#E69F00", "#999999", "#E69F00", "#999999", "#E69F00",
# "#999999", "#E69F00", "#999999", "#E69F00", "#999999", "#E69F00",
# "#999999", "#E69F00", "#999999"))
p
this is the stacked area plot the the above code creates, notice the dates are not chronological
答案 0 :(得分:0)
您必须使用as.Date或as.Posixct函数解析日期。
例如:
gather_data1$Date <- as.Date(gather_data1$Date,format = "%m/%d/%y")
您可以使用的ggplot:
p <- ggplot(gather_data1, aes(x = Date, y = RA, group = zOTU, fill = zOTU)) +
geom_area(position="fill", color = "black")+
scale_x_date(date_labels="%b %Y", date_breaks ="3 month")