用一個資料樣本如下:
df <- structure(list(date = structure(c(18901, 18902, 18903, 18904,
18905, 18906, 18907, 18908, 18909, 18910, 18911, 18912, 18913,
18914), class = "Date"), value = c(190.3, 174.9, 163.2, 168.4,
168.6, 168.2, 163.5, 161.6, 172.9, 166.5, 175.2, 197.7, 212.1,
177.9), type = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L)), row.names = c(NA, -14L), class = "data.frame")
首先,我將type和轉換date為適當的資料型別:
df$type <- as.factor(df$type)
df$date <- as.Date(df$date)
我試圖根據type不同的顏色同時繪制這個時間序列資料。
問題是我無法設定自定義顏色并且區域之間的差距有點大。
ggplot(data=df, aes(x=date, y=value, group=type))
geom_area(fill=df$type, alpha=0.4)
geom_line(color=df$type, size=1)
geom_point(size=2, color=df$type)
scale_color_manual(values=c("gray", "red", "blue"))
出去:

如何重現類似于下面效果的圖形?真誠的感謝。

uj5u.com熱心網友回復:
對于顏色,我建議:
df$type = as.factor(df$type)
ggplot(df, aes(x=date, y=value, group=type,
color = type, fill = type))
geom_area(alpha=0.4)
geom_line(size=1)
geom_point(size=2)
scale_color_manual(values=c("1" = "gray", "2" = "red", "3" = "blue"),
aesthetics = c("color", "fill"), name = "type")

編輯 - 為了消除差距,我們可以重復每個條目的第一個條目type并將它們分配給之前的type.
library(dplyr)
df %>%
group_by(type) %>%
filter(row_number() == 1) %>%
ungroup() %>%
mutate(type = lag(type),
date = date - 0.0001) %>% # w/o this the values stack at boundaries
bind_rows(df) %>%
ggplot(aes(x=date, y=value, group=type,
color = type, fill = type))
...

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358873.html
上一篇:使用沒有.tif和.shp檔案的ggplot2創建柵格
下一篇:在R中繪制資料幀串列
