0

I have a time series dataset in which the x-axis is a list of events in reverse chronological order such that an observation will have an x value that looks like "n-1" or "n-2" all the way down to 1.

I'd like to make a line graph using ggplot that creates a smooth, continuous line that connects all of the points, but it seems when I try to input my data, the x-axis is extremely wonky.

The code I am currently using is

library(ggplot2)

theoretical = data.frame(PA = c("n-1", "n-2", "n-3"),
                         predictive_value = c(100, 99, 98));

p = ggplot(data=theoretical, aes(x=PA, y=predictive_value)) + geom_line();
p = p + scale_x_discrete(labels=paste("n-", 1:3, sep=""));

The fitted line and grid partitions that would normally appear using ggplot are replaced by no line and wayyy too many partitions.

  • 1
    There is insufficient information here to re-create the problem. Please check out [how to create a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for tips on how to include sample data se we can actually run the code to see the same thing you are. Otherwise, it's very difficult to help you. – MrFlick Oct 10 '14 at 14:41
  • "Wonky" is not a helpful descriptor. It would be helpful to provide a (small) example of the data that is causing the behavior. – Roger Fan Oct 10 '14 at 14:42
  • thanks, I think I've updated it well enough. – Matthew Yaspan Oct 10 '14 at 16:14

1 Answers1

0

When you use geom_line() with a factor on at least one axis, you need to specify a group aesthetic, in this case a constant.

p = ggplot(data=theoretical, aes(x=PA, y=predictive_value, group = 1)) + geom_line()
p = p + scale_x_discrete(labels=paste("n-", 1:3, sep=""))
p

If you want to get rid of the minor grid lines you can add

theme(panel.grid.minor = element_blank())

to your graph.

Note that it can be a little risky, scale-wise, to use factors on one axis like this. It may work better to use a typical continuous scale, and just relabel the points 1, 2, and 3 with "n-1", "n-2", and "n-3".

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294