2

I'm trying to overlay two line graphs on the same space using R and a shiny web application.

This is the only example I can find with a similar problem, but I don't see how they relate. This is also the only plot that exhibits this problem; the rest of my shiny application graphs are fine.

My code (relevant parts) is

x1 <- c( 10, 25, 19)
x2 <- c( 3, 24, 11)
x3 <- c( 4, 15, 1)
df <- data.frame( "October" = x1, "November" = x2, "August"=x3)
x <- factor(1:3, labels = c("October", "November", "August"))
t1 <- as.numeric(df[1,1:3])
t2 <- as.numeric(df[2,1:3])
plot(t1 ~ x, type="n", ylim=c(min(t1),max(t2)))
lines(t1 ~ x, col="blue")
lines(t2 ~ x, col="red")

But no matter what I change the type of the initial plot to, it gives me horizontal lines at all the plotted points. I originally had it as type="l" but it did the same thing, so I manually added the line that belongs there, and tried to make the horizontal bars disappear with type="n" Does anyone have any insight into this problem.

I'd prefer solutions in base R, so not using ggplot.

enter image description here

Matthew Ciaramitaro
  • 1,184
  • 1
  • 13
  • 27
  • 1
    It's a lot easier to help if you provide a minimal reprex. I get: `Error: object 'dataframerow1' not found` – Maurits Evers Feb 16 '18 at 02:33
  • that was a generic name I picked because the object is the row of a dataframe. I'll define them though. – Matthew Ciaramitaro Feb 16 '18 at 02:53
  • It's best to make your example self-contained (and minimal). Meaning that if somebody copy&pastes your code into an R terminal it should run without an error. Have a [read on how to provide a minimal reproducible example/attempt](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Maurits Evers Feb 16 '18 at 02:56
  • It should run now – Matthew Ciaramitaro Feb 16 '18 at 03:02
  • Possible duplicate of [Tricks to override plot.factor?](https://stackoverflow.com/questions/15116901/tricks-to-override-plot-factor) – tpol Feb 16 '18 at 03:15

1 Answers1

3

Because x is a factor, plot(t1 ~ x) actually produces a barplot. You only have one measurement per month, so all you see is a horizontal line.

You could do the following:

plot.default(t1 ~ x, type="n", ylim=c(min(t1),max(t2)), xaxt = "n");
axis(1, at = as.numeric(x), labels = levels(x))
lines(t1 ~ x, col="blue")
lines(t2 ~ x, col="red")

enter image description here

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68