简体   繁体   中英

Change x-axis intervals to be monthly in r

I have a data frame with the first column named "Date." It has values like "2016-01-01, 2016-01-02..." etc. The second column is named "precipBulk," and it just has decimal values (ex. 3.36, 1.57, etc.). The third column is named "abundance," and it also has decimal values. I want to graph both "abundance" and "precipBulk" on one graph(Like the image), but I want the x-axis to have intervals with every month instead of every other month like it is now. I know there's a way to do it in ggplot2 using "scale_x_date()" but I can't graph both of the y values in one graph with ggplot2 for some reason. Is there a way to do it without using ggplot2? if not, any tips on how I would graph dual y-axis to achieve this with ggplot2?

Graph link https://i.stack.imgur.com/SZXgT.png ` Small portion of data frame https://i.stack.imgur.com/PvTED.png

To make the graph, I did:

x = frame$Date
y1 = frame$precipBulk
y2 = frame$abundance

plot(x,y1, type = "l",ylab="Bulk Precipitation",xlab="Month",col="blue", main = "Precipitation vs Mosquito Abundance (OSBS 2016)", cex.main = 1)
par(new = TRUE)
plot(x, y2, type = "l",yaxt="n",xaxt="n",ylab="",col="red")
axis(side = 4)
legend('topleft', c("Precipitation", "Mosquito Abundance"), col= c("blue", "Red"),lty=c(1,1), adj = c(0,0.6), cex= 0.75)

You need to turn the x-axis off (as you did) and then add it manually, perhaps reducing the size if necessary so that the axis tick labels fit, otherwise, R will decide for you.

x <- seq(as.Date("2017-01-01"), as.Date("2018-01-01"), "day")
plot(x, rnorm(length(x)), xaxt="n")
at <- seq(min(x), max(x), "month")
axis(side=1, at=at, labels=format(at, "%b"), cex.axis=0.7)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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