![](/img/trans.png)
[英]How to adopt different colors of the geom_smooth line based on its gradient?
[英]geom_smooth(): One line, different colors
我目前正在嘗試自定義我的情節,目標是有一個這樣的情節:
如果我嘗試在aes()或mapping = aes()中指定顏色或線型,我會得到兩個不同的光滑。 每個班級一個。 這是有道理的,因為平滑將針對每種類型應用一次。
如果我在aestetics中使用group = 1
,我會得到一行,也就是一種顏色/線型。
但我無法找到一個解決方案,為每個類都有一條不同顏色/線型的平滑線。
我的代碼:
ggplot(df2, aes(x = dateTime, y = capacity)) +
#geom_line(size = 0) +
stat_smooth(geom = "area", method = "loess", show.legend = F,
mapping = aes(x = dateTime, y = capacity, fill = type, color = type, linetype = type)) +
scale_color_manual(values = c(col_fill, col_fill)) +
scale_fill_manual(values = c(col_fill, col_fill2))
可重現代碼:
文件: 在這里輸入鏈接描述 (我不能讓這個文件縮短並復制它聽到,否則我會因為數據點過少而導致平滑錯誤)
df2 <- read.csv("tmp.csv")
df2$dateTime <- as.POSIXct(df2$dateTime, format = "%Y-%m-%d %H:%M:%OS")
col_lines <- "#8DA8C5"
col_fill <- "#033F77"
col_fill2 <- "#E5E9F2"
ggplot(df2, aes(x = dateTime, y = capacity)) +
stat_smooth(geom = "area", method = "loess", show.legend = F,
mapping = aes(x = dateTime, y = capacity, fill = type, color = type, linetype = type)) +
scale_color_manual(values = c(col_fill, col_fill)) +
scale_fill_manual(values = c(col_fill, col_fill2))
我建議在繪圖函數之外對數據進行建模,然后用ggplot
繪制它。 我使用管道( %>%
)並從tidyverse
mutate
出於方便的原因,但你不必這樣做。 此外,我更喜歡將一條線和一個填充分開,以避免繪圖右側的虛線。
df2$index <- as.numeric(df2$dateTime) #create an index for the loess model
model <- loess(capacity ~ index, data = df2) #model the capacity
plot <- df2 %>% mutate(capacity_predicted = predict(model)) %>% # use the predicted data for the capacity
ggplot(aes(x = dateTime, y = capacity_predicted)) +
geom_ribbon(aes(ymax = capacity_predicted, ymin = 0, fill = type, group = type)) +
geom_line(aes( color = type, linetype = type)) +
scale_color_manual(values = c(col_fill, col_fill)) +
scale_fill_manual(values = c(col_fill, col_fill2)) +
theme_minimal() +
theme(legend.position = "none")
plot
請告訴我它是否有效(我沒有原始數據來測試它),如果你想要一個沒有tidyverse功能的版本。
編輯:
不是很干凈,但使用此代碼可以獲得更平滑的曲線:
df3 <- data.frame(index = seq(min(df2$index), max(df2$index), length.out = 300),
type = "historic", stringsAsFactors = F)
modelling_date_index <- 1512562500
df3$type[df3$index <= modelling_date_index] = "predict"
plot <- df3 %>% mutate(capacity_predicted = predict(model, newdata = index),
dateTime = as.POSIXct(index, origin = '1970-01-01')) %>%
# arrange(dateTime) %>%
ggplot(aes(x = dateTime, y = capacity_predicted)) +
geom_ribbon(aes(ymax = capacity_predicted, ymin = 0, fill = type, group =
type)) +
geom_line(aes( color = type, linetype = type)) +
scale_color_manual(values = c(col_fill, col_fill)) +
scale_fill_manual(values = c(col_fill, col_fill2)) +
theme_minimal()+
theme(legend.position = "none")
plot
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.