4

For educational purpose I'm trying to plot a singel horizontal "numberline" with some datapoints with labels in R. I came this far;

library(plotrix)
source("spread.labels.R")
plot(0:100,axes=FALSE,type="n",xlab="",ylab="")
axis(1,pos=0) 
spread.labels(c(5,5,50,60,70,90),rep(0,6),ony=FALSE, 
labels=c("5","5","50","60","70","90"), 
offsets=rep(20,6))

This gave me a numberline with smaller lines pointing up to (and a little bit "in") the labels from where the datapoints should lie on the numberline - but without the points itself. Can anyone give me additional or alternative R-codes for solving thess problems: - datapoints itself still missing are not plotted, - and labels maybe not evenly divided over the whole numberline, - and lines come into the labels and not merely point to the labels

Thank a lot,

Benjamin Telkamp

Benjamin Telkamp
  • 1,451
  • 2
  • 17
  • 31
  • First, this code is not reproducible. Second, this sounds like it might be easier for others to help you if you upload a picture of what you are trying to accomplish. – JasonAizkalns Aug 17 '15 at 13:52

1 Answers1

5

I usually like to create plots using primitive base R graphics functions, such as points(), segments(), lines(), abline(), rect(), polygon(), text(), and mtext(). You can easily create curves (e.g. for circles) and more complex shapes using segments() and lines() across granular coordinate vectors that you define yourself. For example, see Plot angle between vectors. This provides much more control over the plot elements you create, however, it often takes more work and careful coding than more "pre-packaged" solutions, so it's a tradeoff.

For your case, it sounds to me like you're happy with what spread.labels() is trying to do, you just want the following changes:

  1. add point symbols at the labelled points.
  2. prevent overlap between labels and lines.

Here's how this can be done:

## define plot data
xlim <- c(0,100);
ylim <- c(0,100);
px <- c(5,5,50,60,70,90);
py <- c(0,0,0,0,0,0);
lx.buf <- 5;
lx <- seq(xlim[1]+lx.buf,xlim[2]-lx.buf,len=length(px));
ly <- 20;

## create basic plot outline
par(xaxs='i',yaxs='i',mar=c(5,1,1,1));
plot(NA,xlim=xlim,ylim=ylim,axes=F,ann=F);
axis(1);

## plot elements
segments(px,py,lx,ly);
points(px,py,pch=16,xpd=NA);
text(lx,ly,px,pos=3);

plot

Community
  • 1
  • 1
bgoldst
  • 34,190
  • 6
  • 38
  • 64
  • Beautiful, I played around with the values, so I also understand to change and generalize this. Bgoldst, thank you so much! Benjamin – Benjamin Telkamp Aug 18 '15 at 13:57
  • How do I change the amount of points? also I am setting my xlim to c(0,923) but the nubmer line only goes to 800!!!!! – Sky Scraper Nov 19 '21 at 20:31