我正在尝试使用geom_line和geom_point绘制覆盖两组数据的图。以下是我正在使用的数据。
library(ggplot2)
data <- structure(list(year = c("2017", "2017", "2018", "2018", "2019", "2019"),
month = c("07", "07", "08", "08", "08", "08"),
day = c("04","04", "23", "23", "02", "02"),
treatment = c("XH_ambient_air_1m", "XH_warmed_air_1m", "XH_ambient_air_1m", "XH_warmed_air_1m","XH_ambient_air_1m", "XH_warmed_air_1m"),
average_temp = c(22.1354166666667,23.6472222222222, 19.0044444444444, 19.7804166666667,21.2144444444444,22.1973611111111),
se_temp = c(0.730096702319543, 0.987515579446095,0.893437294439744, 0.852850129052693,1.29506347070289, 1.28123325200788),
average_par = c(0.15899143259508, 0.163376534565775, 0.125768508018743,0.0725347340236767, 0.100666666666667, 0.0886666666666667),
se_par = c(0.00664097819897585,0.0503344693576486, 0.0471636886635353, 0.0164506072528991,0.0364249609166266,0.0324054179283513)),
row.names = c(NA, -6L),
class = "data.frame")
这是我到目前为止在ggplot中所做的。我尝试指定group = treatment,但是在运行代码时没有显示任何行。我还尝试过治疗和年份之间的小组互动,但这也没有用。
ggplot(data, aes(x = month, color = treatment, shape = treatment)) +
facet_grid(.~year) +
geom_point(aes(y = average_temp)) +
geom_point(aes(y = average_par * 100)) +
geom_line(aes(y = average_temp, group = treatment)) +
geom_line(aes(y = average_par * 100, group = treatment)) +
scale_y_continuous(
name = "Air Temperature (°C)",
sec.axis = sec_axis(~./100, name="PAR")) +
theme_classic()
第一个图像是输出图,第二个图像是我(很糟糕)我想要的外观的photoshop版本。在我的photoshop版本中,图例也会更改,但我不想永远花时间修复它。
使用R版本3.5.1,Mac OS X 10.13.6
答案 0 :(得分:2)
无需刻面即可获得非常相似外观的方法如下:
library(ggplot2)
data$date <- factor(paste(data$year, data$month, sep = "\n"),
levels = apply(expand.grid(unique(data$month),
unique(data$year))[2:1],
1, paste, collapse = "\n"))
ggplot(data, aes(x = date, color = treatment, shape = treatment)) +
geom_point(aes(y = average_temp)) +
geom_point(aes(y = average_par * 100)) +
geom_line(aes(y = average_temp, group = treatment)) +
geom_line(aes(y = average_par * 100, group = treatment)) +
scale_y_continuous(name = "Air Temperature (\u00b0C)",
sec.axis = sec_axis(~./100, name="PAR")) +
scale_x_discrete(drop = FALSE,
labels = rep(unique(data$month), length(unique(data$year)))) +
geom_label(inherit.aes = FALSE,
data = data.frame(x = 2 * 1:(length((levels(data$date)))/2) - 0.5,
y = 1.1 * max(data$average_temp),
lab = paste(" ",
sort(unique(data$year)),
" ")),
aes(x, y, label = lab)) +
theme_classic()
由reprex package(v0.3.0)于2020-07-24创建
答案 1 :(得分:2)
也许您正在寻找这个:
ym <- c(paste0(data$year,'_',data$month))
data1 <- data.frame(data,ym)
ggplot(data1, aes(x = ym, color = treatment, shape = treatment)) +
#facet_grid(.~year) +
geom_point(aes(y = average_temp)) +
geom_point(aes(y = average_par * 100)) +
geom_line(aes(y = average_temp, group = treatment)) +
geom_line(aes(y = average_par * 100, group = treatment)) +
scale_y_continuous(
name = "Air Temperature (°C)",
sec.axis = sec_axis(~./100, name="PAR")) +
theme_classic()+
theme(legend.position="bottom")
提供以下输出: