绘制月度值,以年为单位制作x轴标签

时间:2017-10-22 17:25:02

标签: r plot ggplot2

我有一个像这样的数据框:

df<- data.frame( year= c(rep(1982,12), 
rep(1983,12),rep(1984,12),rep(1985,12),rep(1986,12)), month= 
seq(1,60,1), hym= rnorm(60, 0.3, .01), dip= rnorm(60, 0.5, 
.01))

我想按照hym的预测来绘制dipmonth的图表,但是希望将年份放在x轴上,以便更容易地解释这些变量随时间的变化。

我使用以下代码生成图表:

 op <- par(cex.main = 1.5, mar = c(5, 6, 4, 5) + 0.1, 
       mgp = c(3.5,1,0), cex.lab = 1.5 , font.lab = 2, 
       cex.axis = 1.3, bty = "n", las = 1)

 plot(df$month, df$hym,col = "black", pch = 21, bg = "grey", cex = 2,
 xlim = c(1,60), ylim = c(0.2,0.4), ylab = "", xlab = "", 
 axes = FALSE)
 points(df$month, df$dip,col = "red", pch = 21, cex = 2)
 abline(lm(hym~ month, data= df))
 abline(lm(dip~ month, data= df),col="red")
 axis(1)
 axis(2) 
 par(las = 0)
 mtext("Month", side = 1, line = 2.5, cex = 1.5)
 mtext("% Parasitism", side = 2, line = 3.7, cex = 1.5)
 text(10, 0.4, "Hymenoptera", cex = 1, font = 1, adj = 0)
 points(5, 0.4, pch = 21, lwd = 2, cex = 1.5,col = "black",  bg = 
 "grey")
 text(10, 0.35, "Diptera", cex = 1, font = 1, adj = 0)
 points(5, 0.35, pch = 21, lwd = 2, cex = 1.5,col = "red")

我遇到的问题是修改x轴标签而不改变数据的绘制方式。我希望按month绘图,但是使用原始df中的year变量将x轴更改为年增量。在我的实际数据中,我有0到200个月的数据,如果我可以从第一年(例如1982年)开始然后在去年结束(例如1986年)并且在2年内标记轴,则将更容易阅读。增量。

1 个答案:

答案 0 :(得分:1)

尝试一下:

library(tidyverse)
library(lubridate)

# Convert to a tibble
df <- as_tibble(df)

# Modify months for lubridate
df <- df %>% 
  mutate(month_1 = rep(1:12, times = 5))

# Make month numbers named
df$month_1 <- lubridate::month(df$month_1, label = TRUE)

# Combine year and month into a single variable
df <- df %>% 
  mutate(date = paste(month_1, year, sep = " "))

# Model for the line you want in the plot
model_1 <- lm(df$hym ~ df$month)

# The plot itself
df %>% 
  ggplot(aes(reorder(date, month), hym)) +
  geom_point(aes(fill=factor(year)), 
             color="black", 
             pch=21, 
             size=5) +
  theme_classic() +
  geom_abline(intercept = model_1$coefficients[1],
              slope = model_1$coefficients[2]) +
  ylim(0.2, 0.4) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(title = "Parasitism ~ Year",
       x = "Year",
       y = "% Parasitism") +
  guides(fill = guide_legend(title = "Year")) +
  annotate("text", x = 10, y = 0.4, label = "Hymenoptera") +
  annotate("text", x = 8.9, y = 0.35, label = "Diptera") +
  annotate("point", size = 3, x = 7, shape = 1, color = "red", y = 0.35) +
  annotate("point", size = 3, shape = 1, x = 7, y = 0.4) +
  scale_x_discrete(breaks = c("Jan 1982", 
                              "Jan 1983", 
                              "Jan 1984", 
                              "Jan 1985",
                              "Jan 1986"))

返回:

enter image description here