简体   繁体   English

一个R工作室图中的两个对数y轴直方图

[英]Two logarithmic y axis histograms in one R studio diagram

I am using RStudio to draw the histogram of the values in this data . 我正在使用RStudio绘制此数据中值的直方图。

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: 并得到以下直方图:

在此处输入图片说明 在此处输入图片说明 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 ie, 0, 1, 2, 4, 8, 16, ... is also useful). 1-记录了y轴,这样我将得到0、10、100、1000、10000等值,而不是0、4000、8000和12000(log2,即0、1、2、4、8、16 ,...也很有用)。

2- Have the two diagrams in a single diagram (preferably with bars of two different colors/patterns). 2-将两个图放在一个图中(最好使用两种不同颜色/图案的条形图)。 In the resulting diagram, the two bars for each x-value would be beside each other like this: 在结果图中,每个x值的两个条形将彼此相邻,如下所示: 在此处输入图片说明

I tried this solution but got the following error: 我尝试了此解决方案,但收到以下错误:

NULL 空值

Warning message: In (function () : Only one RStudio graphics 警告消息:在(功能()中):仅一个RStudio图形

device is permitted 允许设备

Here's how I did it: 这是我的操作方式:

## 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)

which results in this: 结果是:

在此处输入图片说明

If you would like them to be next to each other, just add 如果您希望它们彼此相邻,只需添加

par(mfrow = c(1, 2)) 

at the top and change the plot command for y to ` 在顶部,将y的plot命令更改为`

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

The resulting plot looks like this: 结果图如下: 在此处输入图片说明

Here's the solution I devised inspired from Teja_K 's answer: 这是我根据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)

And the result: 结果: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM