Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I plot a 1-D plot in R?

Tags:

plot

r

I have a vector of integers, e.g.: 2,8,11,19.

I would like to plot a line of length e.g. 20 then plot a dot for each value that exist in the list (at some constant height), so I get something like this:

-+-----+--+-------+-

like image 785
David B Avatar asked Sep 26 '10 16:09

David B


3 Answers

library(lattice)


x <- c(2, 8, 11, 19)
stripplot(x)

you can adjust the scales to your liking. see ?stripplot

like image 83
Greg Avatar answered Oct 13 '22 01:10

Greg


Brandon Bertelsen is really close...

x <- c(2,8,11,19)
x <- data.frame(x,1) ## 1 is your "height"
plot(x, type = 'o', pch = '|', ylab = '')

But I wrote this mostly to mention that you might also in base graphics look at stripchart() and rug() for ways to look at 1-d data.

like image 35
John Avatar answered Oct 13 '22 00:10

John


This can be done using ggplot2 by removing all the axis and plotting on a constant y value. You can then use the usual ggplot2 functions to change the colours of the dots, and annotate with text, more lines etc.

enter image description here

library(ggplot2)

x=c(2,8,11,19)

ggplot(data.frame(x), aes(x=x, y=0)) +
  geom_point(size = 10)  +
  annotate("segment",x=1,xend=20, y=0, yend=0, size=2) +
  annotate("segment",x=1,xend=1, y=-0.1,yend=0.1, size=2) +
  annotate("segment",x=20,xend=20, y=-0.1,yend=0.1, size=2) +
  geom_text(aes(label = x), col="white") +
  scale_x_continuous(limits = c(1,20)) +
  scale_y_continuous(limits = c(-1,1)) +
  scale_color_manual(values = unname(colours)) + 
  theme(panel.background = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank())

This plot is essentially a straight line centered around 0 with two more line segments added at the ends as stoppers. annotate("segment",...) is preferential to a reference line as you can control how long the line is drawn.

like image 24
Andrew Haynes Avatar answered Oct 13 '22 01:10

Andrew Haynes