如標題所述,我想連接每個組中的點而不是所有點。
這是原始日期:
df<-structure(list(TN = c(13.6, 18, 18.5, 17, 16.9, 13.6, 17.6, 14.8,
14, 11, 12.6, 18.6, 18.8, 18.3, 19.4, 18.5, 18.9, 22, 22.3),
TX = c(29.9, 26.9, 30.5, 26.6, 25.4, 29.7, 24.1, 21.1, 23.8,
29.3, 34.4, 31.1, 32, 35.9, 36.7, 37.5, 39.2, 34.8, 33.6),
TM = c(22.5, 21.4, 23.3, 21.4, 20.2, 21.4, 19.9, 17.8, 18.9,
20.9, 24.5, 24.5, 25.1, 27.3, 28.2, 28.5, 29.2, 28.2, 26.8
), Date = c("01/06/2022", "02/06/2022", "03/06/2022", "04/06/2022",
"05/06/2022", "06/06/2022", "07/06/2022", "08/06/2022", "09/06/2022",
"10/06/2022", "11/06/2022", "12/06/2022", "13/06/2022", "14/06/2022",
"15/06/2022", "16/06/2022", "17/06/2022", "18/06/2022", "19/06/2022"
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-19L))
這是我的代碼:
library(ggplot2)
library(tidyr)
library(dplyr)
df %>% select(Date, TN, TX) %>%
pivot_longer(cols = c(TN,TX), names_to = "Tcombine", values_to = "Value") %>%
ggplot(aes(Date, Value,group = 1,shape=Tcombine,color=Tcombine))
geom_point()
geom_line()
theme(axis.text.x = element_text(angle = 90, hjust = 1), axis.title.x=element_blank())
我希望隨著日期的變化將兩組(兩種顏色)的點分別連接,但不知道為什么所有點都連接?

這是我得到的最終圖表:
歡迎提出任何建議!提前謝謝你!
uj5u.com熱心網友回復:
添加group=Tcombine.
df %>% select(Date, TN, TX) %>%
pivot_longer(cols = c(TN,TX), names_to = "Tcombine", values_to = "Value") %>%
ggplot(aes(Date, Value,group = 1,shape=Tcombine,color=Tcombine))
geom_point()
geom_line(aes(group = Tcombine))
theme(axis.text.x = element_text(angle = 90, hjust = 1), axis.title.x=element_blank())

順便說一句,雖然您的 x 軸排序在這里有效,但當您再獲得一個月時,它就會中斷。我建議您將Date列轉換為適當的Date-class 并添加scale_x_date.
df %>%
mutate(Date = as.Date(Date, format = "%d/%m/%Y")) %>%
select(Date, TN, TX) %>%
pivot_longer(cols = c(TN,TX), names_to = "Tcombine", values_to = "Value") %>%
ggplot(aes(Date, Value,group = 1,shape=Tcombine,color=Tcombine))
geom_point()
geom_line(aes(group = Tcombine))
scale_x_date(date_breaks = "1 day")
theme(axis.text.x = element_text(angle = 90, hjust = 1), axis.title.x=element_blank())

雖然這看起來非常相似,但您可以更好地控制中斷(例如,date_breaks = "3 days")和格式(例如,date_labels ="%d/%m/%Y"如果您真的想要日期的格式)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/524087.html
