Search code examples
rhistogramrstudiologarithm

Two logarithmic y axis histograms in one R studio diagram


I am using RStudio to draw the histogram of the values in this data.

data = read.table("C:\\Test\\test.csv", header=TRUE, sep=",")
hist(data$a, breaks=100)
hist(data$b, breaks=100)

and got the following histograms:

enter image description here enter image description here But I want to:

1- have the y axis logged so that instead of values 0, 4000, 8000 and 12000 I'll have 0, 10, 100, 1000, 10000 and so on (log2 i.e., 0, 1, 2, 4, 8, 16, ... is also useful).

2- Have the two diagrams in a single diagram (preferably with bars of two different colors/patterns). In the resulting diagram, the two bars for each x-value would be beside each other like this: enter image description here

I tried this solution but got the following error:

NULL

Warning message: In (function () : Only one RStudio graphics

device is permitted


Solution

  • Here's the solution I devised inspired from Teja_K 's answer:

    data = read.table("C:\\test\\test.csv", header=TRUE, sep=",")
    par( mar=c(3.1, 5.1, 0, 0)) 
    hist.x <- hist(data$a, plot = FALSE, breaks=50)
    hist.x$counts <- log10(hist.x$counts + 1)
    plot(hist.x, col = rgb(0, 0, 1, 0.99), main="", xlab="", ylab="", yaxt="n")
    yAxesTitles=c(1, 10, 100, 1000, 10000)
    axis(2, at=c(0, 1, 2, 3, 4),labels=yAxesTitles, col.axis="black", las=2)
    mtext(side = 1, text = "Number", line = 2)
    mtext(side = 2, text = "Frequency", line = 4)
    # Adding the second diagram to the first one:
    relocatedData=data$b+0.2
    hist.y <- hist(relocatedData, plot = FALSE, breaks=50)
    hist.y$counts <- log10(hist.y$counts + 1)
    plot(hist.y, col = rgb(1, 0, 0, 0.99), main="", xlab="", ylab="", yaxt="n", add=TRUE)
    legend(7.5, 4, c("a", "b"), lwd=c(1, 1), col=c(rgb(0, 0, 1, 0.99), rgb(1, 0, 0, 0.99)), pch = c(15, 15), pt.cex=2)
    

    And the result: enter image description here