2017-07-25 99 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

是的,我知道了。谢谢!! 有什么方法可以避免标签重叠? –