1

I'm trying to produce a fairly simple stacked histogram with geom_bar but the values on the vertical do not reflect the values passed to the call to ggplot.

the code I'm using:

p<-ggplot(data0, aes(x=variable, y=as.numeric(value), fill=season) )
p+geom_bar(stat='identity')+  facet_grid(specie~region) + ...

where str(data0) reads:

'data.frame':   720 obs. of  5 variables:
 $ specie  : Factor w/ 5 levels "","ozone.DU",..: 3 3 3 3 4 4 4 4 5 5 ...
 $ season  : Factor w/ 5 levels "","autumn (SON)",..: 3 4 2 5 3 4 2 5 3 4 ...
 $ region  : num  1 1 1 1 1 1 1 1 1 1 ...
 $ variable: Factor w/ 15 levels "3","4","5","6",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value   : Factor w/ 736 levels "","1.872389649",..: 28 35 20 12 26 33 19 11 5

The bars produces do not reflect any value of the dataframe, and rise constantly with the value!

the values of the bars are not what I'd expect

any suggestion is welcome. Thanks

efz
  • 425
  • 4
  • 9
  • See http://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information. (This question is likely of limited use in the future since the problem is not related to ggplot2.) – Sam Firke Dec 11 '15 at 13:50

1 Answers1

4

Your problem is with as.numeric of a factor. You're not going to be obtaining the numeric value of the factor but rather the ordered value of the factor. Do test <- as.numeric(data0$value) and look at the result of the test.

What you need to do is not to convert the data0$value column to a factor at all when you receive the dataset.

black_sheep07
  • 2,308
  • 3
  • 26
  • 40
  • 1
    Although it's better not to have your numeric values converted to factor in the first place, given that they are factors, you can also do `as.numeric(as.character(data0$value))` (or, within `aes` in ggplot `as.numeric(as.character(value))`) to convert back to the correct numeric values. – eipi10 Dec 11 '15 at 20:23