0
votes

how to Combine a bar chart and line in single plot in R (from different data sources)?

Say I have two data sources as:

barData<-c(0.1,0.2,0.3,0.4) #In percentage
lineData<-c(100,22,534,52,900)

Note that they may not be in the same scale.

Can I plot both barData and LineData in one plot and make them good looking ?

I cant use ggplot in this case so this is not a duplicated question..

Something like the following:enter image description here

1
Well, what should the result look like? Any tries? Two-axes plots is not one of R's strengths, so I doubt the result is gonna be good looking. Not a strength probably because it's not good practice to do so anyway...lukeA
@lukeA I really need such a graph. The data could be normalized to be in the same scale. Because one is in percentage, another one is real numbers. Thanks for posting anyway.GeekCat
As I said, I dunno what it should look like. Like this? barData<-c(1,2,3,4,5,6);lineData<-c(100,22,534,52,900, 1000);x <- barplot(barData)[, 1];y <- scales::rescale(lineData, to = range(barData));lines(x, y);axis(4, at = pretty(range(barData)), labels = pretty(range(lineData)))?lukeA
@lukeA, I have edit my question as above, would you mind to look at the example picture ? The X-Axis will be Dates, the vertical Axis on the right is not needed.GeekCat

1 Answers

3
votes

Maybe this helps as a starting point:

par(mar = rep(4, 4))
barData<-c(0.1,0.2,0.3,0.4) * 100
y <- lineData<-c(100,22,534,900);
x <- barplot(barData, 
             axes = FALSE,
             col = "blue", 
             xlab = "",
             ylab = "",
             ylim = c(0, 100) )[, 1]
axis(1, at = x, labels = c("Julia", "Pat", "Max", "Norman"))
ats <- c(seq(0, 100, 15), 100); axis(4, at = ats, labels = paste0(ats, "%"), las = 2)
axis(3, at = x, labels = NA) 
par(new = TRUE)
plot(x = x, y = y, type = "b", col = "red", axes = FALSE, xlab = "", ylab = "")
axis(2, at = c(pretty(lineData), max(lineData)), las = 2) 
mtext(text="Lines of code by Programmer", side = 3, line = 1)
box()

enter image description here