merija
merija

Reputation: 215

Is it possible to plot Excel-style plots in R?

enter image description here

Am writing a project with others. They've done some analysis in Excel, and have plotted charts like the one above. I am coding my stuff in R and while not necessary, we'd like it if the plots had a similar style.

While I could export my data to Excel, it got me thinking: Would it be possible to create a plot in R but with the graphics above? Either a direct package that does that, or maybe some complicated way to manually do it?

I have no other experience with plot creation other than the usual plot function and ggplot.

Upvotes: 1

Views: 1285

Answers (1)

Greg Snow
Greg Snow

Reputation: 49640

My first thought was fortune(197):

If anything, there should be a Law: Thou Shalt Not Even Think Of Producing A Graph That Looks Like Anything From A Spreadsheet. -- Ted Harding (in a discussion about producing graphics) R-help (August 2007)

But your example graph is better than what I usually expect from Excel and there is something to be said for matching styles. The plotrix package has some plotting functions whose purpose is to show spreadsheet users that R can do the same thing, then work on converting them to do better things. I don't think that plotrix (or other package) has a tool for your specific plot, so here is some sample code (using just functions from the main packages, no additional needed):

mydata <- data.frame( 
  x1=sort(runif(20,0,2000)),
  y1=sort(runif(20,0,410)),
  x2=sort(runif(20,0,2750)),
  y2=sort(runif(20,0,410)))

par(las=1, xaxs='i',
    yaxs='i')
plot.new()
plot.window(xlim=c(0,3000), 
            ylim=c(0,450))

axis(1, at=seq(0,3000, by=100),
     label=FALSE, tck=1, 
     col.ticks='lightgrey')
axis(2, at=seq(0,450, by=10),
     label=FALSE, tck=1,
     col.ticks='lightgrey')
axis(1, at=seq(0,3000, by=500),
     tck=1, col.ticks='darkgrey')
axis(2, at=seq(0,450, by=50),
     tck=1, col.ticks='darkgrey')
box()

lines( range(mydata$x1,mydata$x2),
         rep(max(mydata$y1),2),
       col='green')
lines( range(mydata$x2, mydata$x1),
         rep(max(mydata$y2),2),
       col='green')

with(mydata, {
  lines(x1,y1, lwd=5, col='blue')
  lines(x1,y1, lwd=3, col='white')
  lines(x2,y2, lwd=5, col='orange')
  lines(x2,y2, lwd=3, col='white')
  points(x1,y1, pch=1, cex=3, col='blue', lwd=2)
  points(x1,y1, pch=1, cex=1.75, col='blue', lwd=2)
  points(x2,y2, pch=1, cex=3, col='orange', lwd=2)
  points(x2,y2, pch=1, cex=1.75, col='orange', lwd=2)
})

You can run this one command at a time to see what each piece does, and each can be customized to better fit what you want. This could be wrapped into a function if you are going to be making multiple similar plots. Some packages may help or expand on this as well.

Upvotes: 1

Related Questions