-4

I'm using lattice's histogram to create a density plot of car's MPG measures:

histogram(~mtcars20$City.MPG)

Histogram 1

For some reason, adding xlim distorts the data:

histogram(~mtcars20$City.MPG,xlim=c(0,30))

Histogram 2

Note that the data is now between 0 and 8 instead of 17 and 24. Does anyone know why this is?

Jan Luba
  • 86
  • 1
  • 8
  • 1
    Can you please include data and/or code that will provide us with a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) ? (I don't have `mtcars20`; I can get `mtcars` via `data(mtcars)`.) I can't replicate the problem with the `mtcars` data set and the `mpg` variable. – Ben Bolker May 14 '16 at 22:48

1 Answers1

1

mtcars$mpg is numeric so there is no problem. mtcars20$City.MPG appears to be a factor, that is, the numbers 1:6 with labels 17, 18, 20, 22,23,24. When you use xlim to start at zero, it interprets that as how you want to relabel the factors. It has no idea that you want the labels to correspond the those numbers. You could use as.numeric(as.character(mtcars20$City.MPG)). But really mpg shouldn't be a factor.

DaveTurek
  • 1,297
  • 7
  • 8
  • It took me a while, but that's what I've figured out eventually, too. Sorry to the previous posters. I wasn't aware that the file was actually a little different from the standard R example file, in that the mpg column did indeed contain factors. Using as.numeric alone did not work, as it didn't give me the numbers, but the factor levels as integers. @DaveTurek's answer might work, but what I did instead was setting `stringsAsFactors=F` when importing the dataset. Sorry for the late response. – Jan Luba May 17 '16 at 22:27