ggplot2时间序列图

2021-03-12  本文已影响0人  灵木er

废话不多说,先看图

image

然后是代码部分

#!/usr/bin/env Rscript
options(warn = -1)
site="https://mirrors.tuna.tsinghua.edu.cn/CRAN"
package_list <- c("tidyverse", "showtext")
for(p in package_list){
    if(!suppressWarnings(suppressMessages(require(p, character.only = TRUE, quietly = TRUE, warn.conflicts = FALSE)))){
        install.packages(p, repos=site)
        suppressWarnings(suppressMessages(library(p, character.only = TRUE, quietly = TRUE, warn.conflicts = FALSE)))
    }
}

library(tidyverse)
library(lubridate)
library(showtext)

font_add("kaiti", "simkai.ttf")
showtext_auto()

input_table = "used.G"
year_show = 2021
nr = 3
output_picture = "used.pdf"

df <- read_delim(input_table, delim = " ", col_names = F) %>% filter(str_detect(X3, "G")) %>% 
    mutate(mem = as.numeric(str_remove(.$X3, "G")))%>%drop_na() %>% 
    group_by(X1) %>% summarise(daymean = mean(mem),daymax = max(mem), daymin = min(mem))

p <- df %>% filter(year(X1)==year_show) %>% ggplot(aes(x = X1)) + geom_line(aes(y = daymean, color="red"))+ 
    geom_line(aes(y = daymax, color="blue")) + geom_line(aes(y = daymin, color="green"))+ 
    scale_colour_discrete(breaks = c('blue','green','red'), labels = c('maxMem','minMem','meanMem')) + 
    facet_wrap(~month(X1), scales = "free", nrow = nr) + 
    labs(title = str_c(year_show, "年memory use"), x = "", y = "Memory\tG", col = "") + theme_classic() + 
    scale_x_date(breaks = df$X1, labels = str_c(month(df$X1), "月", day(df$X1), "日"))+
    theme(legend.position = 'top', axis.text.x = element_text(angle = -90, hjust = 0.5), 
          axis.text = element_text(family = "kaiti", size = 12),
          plot.title = element_text(hjust = 0, vjust = -12),
          legend.text = element_text(size = 12)) # %>% 
p
ggsave(output_picture, p, width = 16, height = 9, units = "in")

没有注释,看不懂的就去学习吧。如果没有simkai.ttf这个字体会报错。需要选择你电脑上有的中文字体。

对了,数据是这样的

2020/04/10 23:00:01 154G
2020/04/10 23:10:01 154G
2020/04/10 23:20:01 154G
2020/04/10 23:30:01 154G
2020/04/10 23:40:02 154G
2020/04/10 23:50:01 154G
2020/04/11 00:00:01 154G
2020/04/11 00:10:01 154G
2020/04/11 00:20:01 154G
2020/04/11 00:30:01 154G
上一篇 下一篇

猜你喜欢

热点阅读