Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bar plot: Bar width based on time - R

Is there a way to create a bar plot, where the width of the bars are relative to the period of time which the data represent?

df <-read.table(file="x.txt", header=T, sep="\t", dec=".", na="NA")

> df
            Date_Time           Date_End   data
1  3/23/2015 00:00:00  4/1/2015 23:59:59   0.00
2   4/2/2015 00:00:00 4/14/2015 23:59:59 -34.67
3  4/15/2015 00:00:00 4/20/2015 23:59:59  -4.44
4  4/21/2015 00:00:00 4/24/2015 23:59:59  14.45
5  4/25/2015 00:00:00  5/5/2015 23:59:59  -8.67
6   5/6/2015 00:00:00 5/12/2015 23:59:59 -86.68
7  5/13/2015 00:00:00 5/19/2015 23:59:59  -8.68
8  5/20/2015 00:00:00 5/26/2015 23:59:59 -24.41
9  5/27/2015 00:00:00  6/2/2015 23:59:59  20.46
10  6/3/2015 00:00:00  6/9/2015 23:59:59  31.07
11 6/10/2015 00:00:00 6/16/2015 23:59:59  58.45
12 6/17/2015 00:00:00 6/23/2015 23:59:59   0.62
13 6/24/2015 00:00:00 6/26/2015 23:59:59 -92.45

I would like data to be plotted as a bar plot, with the bar width from Date_Time to Date_End.

like image 345
squishy Avatar asked Dec 30 '25 21:12

squishy


1 Answers

There is a width argument in barplot. In the code below, I add a time difference column, which will be the width of the bars. The longer the time difference from start to end, the larger the bars.

df <-read.table(text="Row_name  Date_Time Date_End   data
1  3/23/2015-00:00:00  4/1/2015-23:59:59   0.00
2   4/2/2015-00:00:00 4/14/2015-23:59:59 -34.67
3  4/15/2015-00:00:00 4/20/2015-23:59:59  -4.44
4  4/21/2015-00:00:00 4/24/2015-23:59:59  14.45
5  4/25/2015-00:00:00  5/5/2015-23:59:59  -8.67
6   5/6/2015-00:00:00 5/12/2015-23:59:59 -86.68
7  5/13/2015-00:00:00 5/19/2015-23:59:59  -8.68
8  5/20/2015-00:00:00 5/26/2015-23:59:59 -24.41
9  5/27/2015-00:00:00  6/2/2015-23:59:59  20.46
10  6/3/2015-00:00:00  6/9/2015-23:59:59  31.07
11 6/10/2015-00:00:00 6/16/2015-23:59:59  58.45
12 6/17/2015-00:00:00 6/23/2015-23:59:59   0.62
13 6/24/2015-00:00:00 6/26/2015-23:59:59 -92.45", header=T,stringsAsFactors =F)

df[[2]] <- strptime(df[[2]], "%m/%d/%Y-%H:%M:%S")
df[[3]] <- strptime(df[[3]], "%m/%d/%Y-%H:%M:%S")
df$difference <-as.numeric(df[[3]]-df[[2]])

barplot(df$data, width=df$difference)

enter image description here

like image 183
Pierre Lapointe Avatar answered Jan 01 '26 11:01

Pierre Lapointe