Home > R > Adding lines or points to an existing barplot

Adding lines or points to an existing barplot

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)

 

About these ads
Categories: R Tags: , , , , , ,
  1. alex
    January 10, 2013 at 11:22 | #1

    Thx, was a great help. I did something with more than four data sets and some barplots and points. So your post was a good starting point.
    Alex

  2. Emy
    February 12, 2014 at 23:50 | #2

    Hi
    Can you please explain what is stolpec1/2? I am trying to your example to do a similar graph. Thank you.
    ES

    • February 13, 2014 at 08:36 | #3

      @Emy, stolpec1 and stolpec2 are names of columns 1 and 2 (but in Slovene). When I create a data.frame in the second line of code, I give the columns explicit names. If you omit the explicit names, you get a ‘weird’ name that may not be pleasant to work with.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: