1

R データフレームには、時間変数があります。データの形式は %a-%b-%d %H:%M:%S です。たとえば、

2015-03-23 20:00:00

以下のデータのみ取得したい

  20:00:00

上記の変数に基づいてテーブルを作成し、折れ線グラフを作成しようとしました:

                     Var1 Var2  Freq
    1 2015-03-24 00:00:00   RT   612
    2 2015-03-24 01:00:00   RT    65
    3 2015-03-24 06:00:00   RT    58
    4 2015-03-24 07:00:00   RT  5132
    5 2015-03-24 08:00:00   RT  4483
    6 2015-03-24 09:00:00   RT 11112

次のコードを使用して、ggplot 折れ線グラフを作成しました。

   library(ggplot2)
   library(stringr)
   ggplot(rtt, aes(x = as.factor(Var1), y = Freq, colour = Var2, group = Var2)) + geom_line(size = 1) +
    xlab("R Vs T") + geom_point() +
    scale_x_discrete(labels = function(x) str_wrap(x, width = 2)) +
    ggtitle("Number of T Vs R - through the day") +
    theme(plot.title=element_text(size=rel(1.2), lineheight = 1 ))

X 軸のデータではなく時間だけが必要で、グラフの X 軸が完全に文字化けしているように見えるため、これから YMD データを削除するにはどうすればよいですか。

4

2 に答える 2

1

時間は時間のみで構成されているため、次のようになります。

library(ggplot2)
rtt$hour <- as.POSIXlt(rtt$Var1)$hour
ggplot(rtt, aes(hour, Freq, col = Var2)) + geom_line()

注:これを次の目的で使用しましたrtt

Lines <- "Var1,Var2,Freq
2015-03-24 00:00:00,RT,612
2015-03-24 01:00:00,RT,65
2015-03-24 06:00:00,RT,58
2015-03-24 07:00:00,RT,5132
2015-03-24 08:00:00,RT,4483
2015-03-24 09:00:00,RT,11112"
rtt <- read.csv(text = Lines, as.is = TRUE)

ここに画像の説明を入力

于 2015-03-29T13:44:19.490 に答える
1

「時間」部分を抽出するには、いくつかのオプションがあります。一部を以下に示します。

 format(as.POSIXct(str1), '%H:%M:%S')
 [1] "20:00:00"

または

 sub('[^ ]+ ', '', str1)
 #[1] "20:00:00"

または

 strftime(str1, format='%H:%M:%S')
 #[1] "20:00:00"

または

 library(lubridate)
 format(ymd_hms(str1), '%H:%M:%S')
 #[1] "20:00:00"

コードは次のggplotように変更できます

 library(ggplot2)
 ggplot(rtt, aes(x= factor(strftime(Var1, format='%H:%M:%S')),
     y= Freq, colour=Var2, group=Var2)) +
     xlab("R Vs T") +
     geom_point() + 
     scale_x_discrete(labels = function(x) str_wrap(x, width = 2)) +
     ggtitle("Number of T Vs R - through the day") +
     theme(plot.title=element_text(size=rel(1.2), lineheight = 1 ))

アップデート

「時」の部分だけを抽出する必要がある場合

 library(lubridate)
 hour(ymd_hms(str1))
 #[1] 20

データ

 str1 <- '2015-03-23 20:00:00'

 rtt <- structure(list(Var1 = c("2015-03-24 00:00:00", 
 "2015-03-24 01:00:00", 
 "2015-03-24 06:00:00", "2015-03-24 07:00:00", "2015-03-24 08:00:00", 
 "2015-03-24 09:00:00"), Var2 = c("RT", "RT", "RT", "RT", "RT", 
 "RT"), Freq = c(612L, 65L, 58L, 5132L, 4483L, 11112L)), 
 .Names = c("Var1", "Var2", "Freq"), class = "data.frame",
  row.names = c(NA, -6L))
于 2015-03-29T06:52:16.590 に答える