Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScatterPlot and ONLY one Histogram plot together

Tags:

r

I want to visualize time series data with a 'scatter plot' and a histogram on the right side, but I haven't been able to figure out how to turn OFF the histogram on the upper side.

Code Example:

install.packages("psych")
library(psych)
data = matrix(rnorm(n=100000,mean=2,sd=1.5), nrow = 100, ncol=1000)
fs = list()
fs$p_Z = 1*(data>2)
n_p = 1;
  for(i in floor(seq(1,dim(data)[2],length.out=n_p)))
{
  scatter.hist(x = rep(1:length(data[,i])), y = data[,i],
               xlab = 'observations',
               ylab = 'log(TPM)',
               title = 'Mixture Plot',
               col = c("red","blue")[fs$p_Z[,i]+1], 
               correl = FALSE, ellipse = FALSE, smooth = FALSE)
}

Result:

scatter plot with two histograms, one upper side and one on right side

Expected Result: Same as the one I have but with no histogram on the upper side. I.e., ONLY the histogram on the right side for log(TPM).

Note: I am using psych package, scatter.hist function which seemed easy and nice to use, but couldn't find how to turn off one histogram.

like image 210
Dnaiel Avatar asked Apr 14 '26 04:04

Dnaiel


1 Answers

Where flexibility ends, hacking begins. If you look at scatter.hist function, you will see that it is pretty basic usage of R base graphics. Following modified code would create the plot you want:

scat.hist <- function(x, y, xlab = NULL, ylab = NULL, title = "", ...) {

## Create layout
layout(matrix(c(1,2),1,2,byrow=TRUE), c(3,1), c(1,3))

## Plot scatter
par(mar=c(5,5,3,1))
plot(x= x, y = y, xlab = xlab, ylab = ylab, main = title, ...)

## Right histogram
yhist <- hist(y, plot = FALSE, breaks = 11)
par(mar=c(5,2,3,1))
mp <- barplot(yhist$density, space=0, horiz=TRUE, axes = FALSE)
## Density
d <- density(y, na.rm = TRUE, bw = "nrd", adjust = 1.2)
temp <- d$y
        d$y <- (mp[length(mp)] - mp[1] + 1) * (d$x - min(yhist$breaks))/(max(yhist$breaks) - min(yhist$breaks))
        d$x <- temp
lines(d)
}

Let's try it for the first row:

i = 1
scat.hist(x = seq_along(data[,i]), y = data[,i], col = c("red", "blue")[fs$p_Z[,i]+1], xlab = 'observations', ylab = 'log(TPM)', title = 'Mixture Plot')

enter image description here

like image 79
Mikko Avatar answered Apr 21 '26 01:04

Mikko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!