2 Variable Barplot, 2 y Axes

I have the following data

test<-data.frame(group=1:10, var.a=rnorm(n=10,mean=500,sd=20), var.b=runif(10)) 

I need a barcode with a 2 y axis (one for var.a, one for var.2). Each group (x axis, 1:10) should have 2 bars next to each other, one for var.a and one for var.b.

I cannot use one y axis due to the difference order of var.a and var.b

Is this possible with a base R?

thanks

+4
source share
1 answer

To use the graphics package in R, you can create new variables, because the values ​​in var.a and var.b converted in proportion to the maximum values ​​in the corresponding variable:

 test <- data.frame(group = 1:10, var.a = rnorm(n = 10, mean = 500, sd = 20), var.b = runif(10)) funProp <- function(testCol) { test[, testCol]/max(test[, testCol]) } test$var.a.prop <- funProp("var.a") test$var.b.prop <- funProp("var.b") 

Then draw a graph using barplot() without axes:

 barplot(t(as.matrix(test[, c("var.a.prop", "var.b.prop")])), beside = TRUE, yaxt = "n", names.arg = test$group) 

Then add the axes to the left and right, using the original ranges of values ​​for the labels (the labels argument) and proportional ranges to place the labels on the axes (the at argument) (this part is not very, but it does its job):

 axis(2, at = seq(0, max(test$var.a.prop), length.out = 10), labels = round(seq(0, max(test$var.a), length.out = 10))) axis(4, at = seq(0, max(test$var.b.prop), length.out = 10), labels = round(seq(0, max(test$var.b), length.out = 10), 2)) 

(Sorry for the missing image)

EDIT:

To get the axes a little pretty er,

 myLeftAxisLabs <- pretty(seq(0, max(test$var.a), length.out = 10)) myRightAxisLabs <- pretty(seq(0, max(test$var.b), length.out = 10)) myLeftAxisAt <- myLeftAxisLabs/max(test$var.a) myRightAxisAt <- myRightAxisLabs/max(test$var.b) barplot(t(as.matrix(test[, c("var.a.prop", "var.b.prop")])), beside = TRUE, yaxt = "n", names.arg = test$group, ylim=c(0, max(c(myLeftAxisAt, myRightAxisAt)))) axis(2, at = myLeftAxisAt, labels = myLeftAxisLabs) axis(4, at = myRightAxisAt, labels = myRightAxisLabs) 
+7
source

Source: https://habr.com/ru/post/1403225/


All Articles