ggplot2直方图/条形图,包含日期和时间

时间:2018-05-30 15:28:34

标签: r ggplot2 charts histogram bar-chart

鉴于此df

       Date     Time     Values 
1 2018-04-02 09:15:00 14.00000
2 2018-04-02 09:30:00  4.00000
3 2018-04-02 09:45:00 20.00000
4 2018-04-02 10:00:00 30.00000
5 2018-04-02 10:15:00 14.00000
6 2018-04-02 10:30:00 31.16667

我尝试按Values排序直方图/条形图,而X轴值为DateTime(两个不同的图表)。这是Time图表的示例:

ggplot(df, aes(reorder(Time, Values)), y=Values) + 
  geom_col(position = "dodge")

我一直在尝试使用geom_colgeom_bar并使用stat =" identity"和其他情况,但似乎没有任何东西适用于两个图表。对于上面的代码,它出现此错误:

Error in as.Date.numeric(value) : 'origin' must be supplied

1 个答案:

答案 0 :(得分:0)

注意var类型(DatefactorPOSIXct):

my_text <- ' Date     Time     Values 
1 2018-04-02 09:15:00 14.00000
2 2018-04-02 09:30:00  4.00000
3 2018-04-02 09:45:00 20.00000
4 2018-04-02 10:00:00 30.00000
5 2018-04-02 10:15:00 14.00000
6 2018-04-02 10:30:00 31.16667'

df <- read.table(text = my_text)
str(df) # factors ...

df$Date <- as.Date(as.character(df$Date))
df$Time <- as.POSIXct(paste(as.character(df$Date), as.character(df$Time)))

str(df) # Date and POSIXct 
library(ggplot2)

ggplot(df, aes(reorder(Time, Values), y = Values)) + 
  geom_col(position = "dodge")

enter image description here