一个R studio图中的两个对数y轴直方图

时间:2015-12-26 01:56:21

标签: r histogram rstudio logarithm

我正在使用RStudio绘制此data中的值的直方图。

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

并得到以下直方图:

enter image description here enter image description here 但我想:

1-记录y轴,以便代替值0,4000,8000和12000而不是0,10,100,1000,10000等等(log2即0,1,2, 4,8,16,...也很有用。)

2-将两个图表放在一个图表中(最好使用两种不同颜色/图案的条形图)。在结果图中,每个x值的两个条形将彼此相邻,如下所示: enter image description here

我试过这个solution,但收到了以下错误:

  

NULL

     

警告信息:In(function():只有一个RStudio图形

     允许

设备

2 个答案:

答案 0 :(得分:1)

以下是我的表现:

## Create fake data
x <- c(rep(1, 100), rep(2, 20000), rep(3, 800), rep(4, 10000))
y <- c(rep(1, 10), rep(2, 1000), rep(3, 10000), rep(4, 2000))

## Plot x
hist.x <- hist(x, plot = FALSE)
hist.x$counts <- log10(hist.x$counts + 1)
plot(hist.x, col = rgb(0, 0, 1, 0.25))

## Plot y
hist.y <- hist(y, plot = FALSE)
hist.y$counts <- log10(hist.y$counts + 1)
plot(hist.y, col = rgb(1, 0, 0, 0.25), add = TRUE)

结果如下:

enter image description here

如果您希望它们彼此相邻,只需添加

即可
par(mfrow = c(1, 2)) 
在顶部

并将y的plot命令更改为“

plot(hist.y,col = rgb(1,0,0,0.25))

结果情节如下所示: enter image description here

答案 1 :(得分:0)

我设计的解决方案源于Teja_K的回答:

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)

结果: enter image description here