我有一个数据框,其中包含90个对象,其中包含6个变量(一个是日期,另一个是3个月的站内温度-在此添加了一部分)。我想针对日期绘制站点温度数据,但是站点1数据应该用点+线绘制和其他站点仅在点中。
df <- data.frame(Date= c(1:20),
Station1 = c(31.7,19.5,23.6,20.5,25.2,35.5,38.0,30.3,20.1,20.6,23.6,33.6,21.1,22.7,24.8,23.5,21.8,20.8,26.9,21.2),
Station2= c(10.3,12.2,13.3,13.4,13.4,14.5,25.1,22.7,16.0,15.8,13.0,16.0,16.9,16.4,17.2,15.8,15.6,16.7,16.8,16.9),
Station3 = c(26.4,15.8,18.0,15.6,22.6,30.4,31.7,26.5,18.2,19.9,23.2,28.0,16.7,20.1,21.4,19.4,20.1,19.8,25.0,20.3),
Station4 = c(8.6,8.8, 7.1,9.3,8.5,13.1,21.6,20.1,12.3,11.7,9.6,14.2,15.9,13.1,13.6,13.1,12.4,11.3,12.5,14.3),
Station5 = c(31.6,22.8,17.0,18.6,28.9,35.5,38.7,30.3,25.7,21.9,28.3,32.7,24.2,26.5,28.1,24.4,24.0,24.6,28.5,22.5))
我尝试过不同的方式,
x <- df$Date
y1 <- df$Station1
y2 <- df$Station2
y3 <- df$Station3
y4 <- df$Station4
y5 <- df$Station5
g1 <- ggplot(df, aes(x)) +
geom_line(aes(y=y1), color = "red")+
geom_point(aes(y=y1), color = "red")+
geom_point(aes(y=y2), color = "#00FF00") +
geom_point(aes(y=y3), color = "blue") +
geom_point(aes(y=y4), color = "#FF9933") +
geom_point(aes(y=y5), color = "purple")
这不会给我一个传说,我也不能添加一个。
而且我尝试使用提迪尔,
PD <- df %>%
gather(type, Temperature, Station1, Station2, Station3, Station4, Station5)
ggplot(PD, aes(x = Date, y= Temperature, color = type)) + geom_point()
它创建了点图,但不能为桩号一做点+线。
也正在尝试此操作,但由于日期成为行名而无法使用。
df1 <- data.frame(St1 = c(df$Station1),
St2 = c(df$Station2),
St3 = c(df$Station3),
St4 = c(df$Station4),
St5 = c(df$Station5),
row.names = c(c(df$DATE)))
q <- df1 %>%
rownames_to_column() %>%
gather(key = key, value = value, St1,St2) %>%
mutate(rowname = factor(rowname)) %>%
ggplot(aes(as.Date(rowname), value, color = key)) +
geom_point() +
geom_line() +
labs(x="Dates", y="temperature", title ="Station temperatures")+
theme_bw()
非常感谢您的帮助,因为我是R的新手。在此先感谢!
如果我对你说对了
library(tidyverse)
df1 <- df %>% pivot_longer(-Date)
ggplot(df1, aes(Date, value, color = name)) +
geom_point() +
geom_line(data = filter(df1, name == "Station1"), aes(Date, value, color = name))
您非常亲密。您需要使用ggplot scale_color_manual()
将颜色与每个工作站相关联。
这是您的第一次尝试的解决方案:
g1 <- ggplot(df, aes(x)) +
geom_line(aes(y=y1, color = "y1"))+ # note that color = "y1" is within aes()
geom_point(aes(y=y1, color = "y1"))+
geom_point(aes(y=y2, , color = "y2")) +
geom_point(aes(y=y3, color = "y3")) +
geom_point(aes(y=y4, color = "y4")) +
geom_point(aes(y=y5, color = "y5")) +
scale_color_manual(name = "Stations", # here is a custom scale that creates legend
values = c("y1" = "red",
"y2" = "#00FF00",
"y3" = "blue",
"y4" = "#FF9933",
"y5" = "purple"))
print(g1)