Adding lines or points to an existing barplot

January 15, 2011
By

(This article was first published on Dang, another error, and kindly contributed to R-bloggers)

Sometimes you will need  to add some points to an existing barplot. You might try

par(mfrow = c(1,2))
df <- data.frame(stolpec1 = 10 * runif(10), stolpec2 = 30 * runif(10))
barplot(df$stolpec1)
lines(df$stolpec2/10) #implicitno x = 1:10
points(df$stolpec2/10) 

but you will get a funky looking line/points. It’s a bit squeezed. This happens because bars are not drawn at intervals 1:10, but rather on something else. This “else” can be seen if you save your barplot object. You will notice that it’s a matrix object with one column – these are values that are assumed on x axis. Now you need to feed this to your lines/points function as a value to x argument and you’re all set.


df.bar <- barplot(df$stolpec1)
lines(x = df.bar, y = df$stolpec2/10)
points(x = df.bar, y = df$stolpec2/10)

Another way of plotting this is using plotrix package. The controls are a bit different and it takes some time getting used to it.


library(plotrix)

barp(df$stolpec1, col = "grey70")
lines(df$stolpec2/10)
points(df$stolpec2/10)

 


To leave a comment for the author, please follow the link and comment on his blog: Dang, another error.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.