2016-04-06 2 views
1

Я пытаюсь сделать ggplot, который показывает частоту в часах. У меня проблема с осью x, я изменил исходный формат даты с 2015-01-02 02:07:27 до 2015-01-02 02, я использовал format(dates, format = "%Y-%m-%d %H"). В моем ggplot я использовал aes aes(x=as.Date(dates).., но по оси x у меня формат 2015-01-02. Можно указать дату по оси x в формате "%Y-%m-%d %H"?
Спасибо за помощь!ggplot x-axis как дата с часами

+0

вы не перезаписать свой прежний формат в 'AES()' ? – mtoto

+1

В R «Дата» - это _only_ день, месяц и год. Поэтому, как только вы используете 'as.Date()', это все, что у вас есть. Если вам нужен час, вам нужен _datetime_, возможно, POSIXct. – joran

+0

Пакет весов имеет функцию date_format, которая должна делать то, что вы ищете. Используйте это в сочетании с функцией scale_x_datetime ggplot. Вот хороший пример: http://stackoverflow.com/questions/11748384/formatting-dates-on-x-axis-in-ggplot2 –

ответ

3

Я просто подумал, что приведу пример, чтобы согласиться с моим комментарием. Вы можете использовать функцию date_format() от весов .

require(ggplot2) 
require(scales) 

#Create a test sequence of dates 
test_dates = seq(from = as.POSIXct("2015-01-02 02:07:27", format="%Y-%m-%d %H:%M:%S"), 
       to = as.POSIXct("2015-01-04 02:00:00", format="%Y-%m-%d %H:%M:%S"), 
       by = "hour") 
#Set seed for random variable 
set.seed(1) 
#Create the test data 
time_data = 
    data.frame(dates = test_dates, 
       measurements = runif(n = length(test_dates), 
            min = 0, max = 1)) 
#Plot the data 
ggplot(time_data, aes(x = dates, y = measurements)) + 
    geom_line() + 
    #Here is where I format the x-axis 
    scale_x_datetime(labels = date_format("%Y-%m-%d %H"), 
        date_breaks = "8 hours") 

Преимущество этого в том, что вам не нужно изменять/переформатировать исходные данные. Вот что полученный график выглядит следующим образом: enter image description here

UPDATE: Вот еще один пример использования тестовых данных из комментариев OP в:

require(ggplot2) 
require(scales) 

#Create the test data 
example_data <- 
    data.frame(a = as.POSIXct(c("2015-01-02 06:07:27", "2015-01-02 06:42:36", "2015-01-02 08:07:38", "2015-01-02 08:08:45", "2015-01-02 08:12:23", "2015-01-03 09:07:27", "2015-01-03 09:42:36")), 
       b = c("1","1","1","1","1","1","1")) 

#Pull out date and hour components 
example_data$days <- as.POSIXct(format(example_data$a, "%Y-%m-%d")) 
#This doesn't work because format just returns a character string, not a dateTime 
example_data$hours <- format(example_data$a, "%Y-%m-%d %H") 
#Instead, you need to re-cast the output of format as a dateTime 
example_data$hours <- as.POSIXct(format(example_data$a, "%Y-%m-%d %H"), format="%Y-%m-%d %H") 

#Plot the data 
ggplot(data = example_data, aes(x=days)) + geom_bar(stat="bin") 
ggplot(data = example_data, aes(x=hours)) + geom_bar(stat="bin") 

#Now use axis-scaling and date_format to get just the data and hours 
ggplot(data = example_data, aes(x=hours)) + 
    geom_bar(stat="bin") + 
    scale_x_datetime(labels = date_format("%Y-%m-%d %H")) 
+0

Большое спасибо за вашу помощь. Это мой маленький пример данных: 'a <- as.POSIXct (c (" 2015-01-02 06:07:27 "," 2015-01-02 06:42:36 "," 2015-01-02 08:07:38 "," 2015-01-02 08:08:45 "," 2015-01-02 08:12:23 "," 2015-01-03 09:07:27 "," 2015-01 -03 09:42:36 ")) b <- c (" 1 "," 1 "," 1 "," 1 "," 1 "," 1 "," 1 ") example_data <- data_frame (a, b) example_data $ days <- as.POSIXct (format (example_data $ a, "% Y-% m-% d")) example_data $ hours <- format (example_data $ a, "% Y-% m -% d% H ")' –

+0

Извините, что я забыл, это мои графики: 'ggplot (data = example_data, aes (x = days)) + geom_bar (stat =" bin ") ggplot (data = example_data, aes (x = часы)) + geom_bar (stat = "bin") 'У меня проблема с часами. –

+0

@ A.Trzcionkowska Я добавил еще один пример, используя ваши тестовые данные выше. В будущем вы можете заглянуть в пакет * lubridate * при работе с dateTimes. Это может сделать вашу жизнь намного проще. –

Смежные вопросы