Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot histograms as lines

Tags:

plot

r

histogram

I want to plot several histograms of time data (1 week long) on the same plot as lines.

I have time data:

> dput(head(ts))
structure(c(1364421605.227, 1364375025.034, 1364376298.393, 1364375002.928, 
1364393158.084, 1364423268.856), class = c("POSIXct", "POSIXt"))

and I want to plot its histogram. hist(ts,breaks=7*24) works fine, but it uses the h plot type which will obscure other histogram plots I want to add (I know I can use transparent colors - rainbow with alpha=0.5, but I really want to see the lines).

I tried

> hist(ts, breaks = 7*24, type="l")
Warning messages:
1: In title(main = main, sub = sub, xlab = xlab, ylab = ylab, ...) :
  graphical parameter "type" is obsolete
Calls: hist -> hist.POSIXt -> myplot -> plot -> plot.histogram -> title
2: In axis(2, ...) : graphical parameter "type" is obsolete
Calls: hist -> hist.POSIXt -> myplot -> axis
3: In axis(side, at = z, labels = labels, ...) :
  graphical parameter "type" is obsolete
Calls: hist -> hist.POSIXt -> myplot -> axis.POSIXct -> axis

why is hist passing type to title?

I can create the histogram object and plot it separately:

> h <- hist(ts, breaks=7*24, plot=FALSE)
> plot(x=h$mids, y=h$density, type="l")

but then the x axis is labeled with numbers (e.d., "1364421605") not dates (e.g., "Mar 25").

I guess I am supposed to use axis, but I would rather not handle that myself - after all, hist constructs just the axis I want!

Thanks!

like image 971
sds Avatar asked May 21 '13 20:05

sds


People also ask

How do you plot multiple histograms in one plot?

To make multiple overlapping histograms, we need to use Matplotlib pyplot's hist function multiple times. For example, to make a plot with two histograms, we need to use pyplot's hist() function two times. Here we adjust the transparency with alpha parameter and specify a label for each variable.


1 Answers

The following looks weird because you only gave us six data points in your dput. You can plot a line plot without the x-axis and add it afterwards like so:

h <- hist(ts, breaks=7*24, plot=FALSE)
plot(x=h$mids, y=h$density, type="l", xaxt="n")
axis(1,at=ts,labels=format(ts,"%b-%d"))

enter image description here

like image 91
Pierre Lapointe Avatar answered Sep 18 '22 06:09

Pierre Lapointe