R : 玉米产量数据

发布时间 2023-10-30 14:20:00作者: 王哲MGG_AI
# 载入必要的库
library(ggplot2)
library(cowplot)

# 创建数据
df <- data.frame(
  year = 2000:2019,
  total_yield = c(26077.89, 25717.39, 25907.07, 26361.31, 26499.22, 24976.44, 24845.32, 22955.90, 21131.60, 19075.18, 17325.86, 17211.95, 15512.25, 15160.30, 13936.54, 13028.711, 11583.02, 12000, 11409, 10600),  # 万吨
  yield_per_acre = c(6316.70, 6104.29, 6110.30, 5967.12, 5892.85, 5808.91, 6015.93, 5869.69, 5747.51, 5453.68, 5258.49, 5555.70, 5166.67, 5326.32, 5287.34, 5120.20, 4812.59, 4870, 4700, 4600),  # 公斤/亩
  imported = c(1.1, 4.6, 1.2, 0.4, 0.8, 1.6, 7.6, 4.9, 5.7, 8.6, 159.3, 176.1, 520.9, 326.9, 260.3, 473.3, 317.3, 283.1, 352.9, 479.9 )  # 万吨
)

# 创建左坐标轴的图形
p1 <- ggplot(df, aes(x = year)) +
  geom_line(aes(y = total_yield, color = "Total Yield")) +
  geom_point(aes(y = total_yield, color = "Total Yield")) +
  geom_line(aes(y = imported, color = "Imported")) +
  geom_point(aes(y = imported, color = "Imported")) +
  scale_color_manual(values = c("Total Yield" = "blue", "Imported" = "red")) +
  labs(y = "万吨", color = "Legend") +
  theme(legend.position = c(0.8, 0.9))

# 创建右坐标轴的图形
p2 <- ggplot(df, aes(x = year)) +
  geom_line(aes(y = yield_per_acre, color = "Yield per Acre")) +
  geom_point(aes(y = yield_per_acre, color = "Yield per Acre")) +
  scale_color_manual(values = c("Yield per Acre" = "green")) +
  labs(y = "公斤/亩", color = "Legend") +
  theme(legend.position = c(0.8, 0.8))

# 合并两个图形
p_combined <- plot_grid(p1, p2, align = "h", ncol = 1, rel_heights = c(1, 0.05))

print(p_combined)