time axis settings for histogram

瀏覽次數:36 次
跳到第一則未讀訊息

Ery Djunaedy

未讀,
2017年9月28日 上午8:39:322017/9/28
收件者:ggplot2
This is a reposting from Stack Overflow:

I am trying to understand how the limit of axis works in ggplot histogram. When I tried to set the limit, the histogram shifted.

Below is a script to generate histogram of kWh for each month. On the first graph (p1) . On the second graph (p2) .

The histograms are attached.

On the first histogram (p1), I did not set the axis limit. The first bar is correct, for Jan and the value is above 20000.

On the second histogram (2), I set the limit, which is the same as the time span of the dataset. The first bar is actually for Feb (see the value is below 20000, which is wrong), but the bar in the histogram says Jan.

My question: what causes this time shift? Furthermore, two bars are missing in the second histogram.

Furthermore, On the third histogram (p3), I extend the time span to include two weeks before and after. All the bars (12 bars) appear. But the first bar is marked 12-2013 instead of 01-2014.

Again, the time shifted.

Any help would be appreciated. Thanks


Lines <- "year,month,kWh
2014,1,21535
2014,2,19826
2014,3,20796
2014,4,21249
2014,5,21442
2014,6,22685
2014,7,20569
2014,8,23346
2014,9,23440
2014,10,20148
2014,11,24415
2014,12,21628"
con <- textConnection(Lines)

df = read.csv(con)

df$timestamp = as.POSIXct(paste(df$year,df$month,"01", sep="-"),
                          format="%Y-%m-%d", tz="GMT")

library(ggplot2)

png(filename = "p1.png", width = 800, height = 400, units = "px", pointsize = 24 )

p1 = ggplot(data = df, aes(x = timestamp, kWh)) +
           geom_bar(stat = "identity") +
     scale_x_datetime(date_breaks = "1 month", 
                      date_labels = "%m\n%Y")
p1 

png(filename = "p2.png", width = 800, height = 400, units = "px", pointsize = 24 )

time.start=as.POSIXct("2014-01-01",format="%Y-%m-%d", tz="GMT")
time.end=as.POSIXct("2014-12-01",format="%Y-%m-%d", tz="GMT")

p2 = ggplot(data = df, aes(x = timestamp, kWh)) +
           geom_bar(stat = "identity") +
     scale_x_datetime(limits = c(time.start,time.end),
                      date_breaks = "1 month", 
                      date_labels = "%m\n%Y")
p2 

png(filename = "p3.png", width = 800, height = 400, units = "px", pointsize = 24 )

time.start=as.POSIXct("2013-12-15",format="%Y-%m-%d", tz="GMT")
time.end=as.POSIXct("2014-12-15",format="%Y-%m-%d", tz="GMT")

p3 = ggplot(data = df, aes(x = timestamp, kWh)) +
           geom_bar(stat = "identity") +
     scale_x_datetime(limits = c(time.start,time.end),
                      date_breaks = "1 month", 
                      date_labels = "%m\n%Y")
p3 












回覆所有人
回覆作者
轉寄
0 則新訊息