2017-07-25 32 views
0

我正在使用g中的ggplot2繪製折線圖。我想以適當的日期格式命名超過特定閾值的點。在ggplot中以正確格式標記日期R

我對繪製的圖形代碼:

ggplot(DateSubset1, aes(TimeStamp)) + 
    geom_line(aes(y = CPU, colour = "Orange")) + 
    geom_line(aes(y = MEM), colour = "Black")+ 
    scale_x_datetime(date_break = "1 days")+ 
    geom_point(aes (x= TimeStamp, y=CPU), size = 1,colour = "Purple", 
     subset(DateSubset1, CPU>25))+ 
    geom_point(aes (x= TimeStamp, y=MEM), size = 1,colour = "Blue", 
     subset(DateSubset1, MEM>10))+ 
    scale_y_continuous(breaks = c(5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80)) 

我的圖表看起來是這樣的:

enter image description here

我要標註這些點(這是超過一定閾值)適當日期格式爲我的數據集。 我試圖

geom_text(aes(y=CPU, label= ifelse(CPU>25, TimeStamp, ''))) 

使用這個我圖的樣子:

enter image description here

geom_text(aes(y= CPU,label= ifelse(CPU>25, format(TimeStamp), format = 
"%y%m%d %h%m%s",''))) 

而且

geom_text(aes(y= CPU, label=ifelse(CPU>25, as.Date(TimeStamp), ''))) 

而且

geom_text(aes(y= CPU, label=ifelse(CPU>25, as.Date.POSIXct(TimeStamp), ''))) 

字符串的數據集:

data.frame':  
1420 obs. of 3 variables: 
$ TimeStamp: POSIXct, format: "2017-06-28 07:03:02" "2017-06-28 07:06:01" 
"2017-06-28 07:09:01" ... 
$ CPU  : num 0.9 0.8 12.2 3.7 2.3 1.7 1.4 1.1 1 0.9 ... 
$ MEM  : num 1.7 1.8 1.5 1.8 1.8 1.8 1.9 1.9 1.9 2.1 ... 

樣本數據是這樣的:

TimeStamp    CPU MEM 
2017-06-28 07:03:02  0.9 1.7 
2017-06-28 07:06:01  0.8 1.8 
2017-06-28 07:09:01  12.2 1.5 
2017-06-28 07:12:01  3.7 1.8 
2017-06-28 07:15:01  2.3 1.8 
+0

請提供示例數據讓你的身材能由他人生成。 –

+0

[標籤點在geom \ _point中]的可能重複(https://stackoverflow.com/questions/15624656/label-points-in-geom-point) –

+0

不是重複的,因爲問題是將文本標籤格式化爲日期 – user101089

回答

0

OK,試試這個代碼:

zz = ' 
    CPU MEM 
    0.9 1.7 
    0.8 1.8 
    12.2 1.5 
' 

df <- read.table(text = zz, header = TRUE) 
df 

TmS = c("2017-06-28 07:03:02", "2017-06-28 07:06:01", "2017-06-28 07:09:01") 
df = cbind(TmS, df) 
df$TmS = as.character(df$TmS) 

label = as.character(ifelse(df$CPU>10, df$TmS, '')) 
df$TmS = as.POSIXct(df$TmS) 


ggplot(df, aes(TmS)) + 
    geom_line(aes(y = CPU, colour = "Orange")) + 
    geom_line(aes(y = MEM), colour = "Black")+ 
    scale_x_datetime(date_break = "1 days")+ 
    geom_point(aes (x= TmS, y=CPU), size = 1,colour = "Purple", 
      subset(df, CPU>10))+ 
    geom_point(aes (x= TmS, y=MEM), size = 1,colour = "Blue", 
      subset(df, MEM>1.5))+ 
    scale_y_continuous(breaks = c(5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80))+ 
    geom_text(aes(y= CPU, label=label)) 
+0

當我嘗試這個時,我看到這個錯誤 - 錯誤在unclass(x)/ 86400:非二進制運算符的數字參數 –

+0

我做了更改。如果您還有其他問題,請告訴我。 – AK88

+0

是的,我知道了。謝謝!! 有什麼方法可以避免標籤重疊? –