2

Really sorry, but I just started with R and am stuck on this now. Despite reading up on other related questions here and already knowing that there was a big change with ggplot2.

This is my table:

'data.frame':   1309 obs. of  11 variables:
 $ survived: Factor w/ 3 levels "0","1","None": 1 2 2 2 1 1 1 1 2 2 ...
 $ pclass  : Factor w/ 3 levels "1","2","3": 3 1 3 1 3 3 1 3 3 2 ...
 $ name    : Factor w/ 1307 levels "Abbing, Mr. Anthony",..: 109 191 358 277 16 559 520 629 417 581 ...
 $ sex     : Factor w/ 2 levels "female","male": 2 1 1 1 2 2 2 2 1 1 ...
 $ age     : num  22 38 26 35 35 NA 54 2 27 14 ...
 $ sibsp   : int  1 1 0 1 0 0 0 3 0 1 ...
 $ parch   : int  0 0 0 0 0 0 0 1 2 0 ...
 $ ticket  : Factor w/ 929 levels "110152","110413",..: 524 597 670 50 473 276 86 396 345 133 ...
 $ fare    : num  7.25 71.28 7.92 53.1 8.05 ...
 $ cabin   : Factor w/ 187 levels "","A10","A14",..: 1 83 1 57 1 1 131 1 1 1 ...
 $ embarked: Factor w/ 4 levels "","C","Q","S": 4 2 4 4 4 3 4 4 4 2 ...

Now, I am trying to create a histogram plot with ggplot2 as shown below, but cannot figure out why I keep getting the error message. Any help would be appreciated.

I am running R Version 1.0.136 on Mac OS 10.12.3

I already tried changing width to binwidth to no avail. I also tried using geom_bar instead of geom_histogram.

ggplot(train, aes(x = pclass, fill = factor(survived))) +
    geom_histogram(width = 0.5) +
    xlab("pclass") +
    ylab("total count") +
    labs(fill = "survived")

Error: StatBin requires a continuous x variable the x variable is discrete. Perhaps you want stat="count"?

Peter Bratton
  • 6,302
  • 6
  • 39
  • 61
Chris Kubik
  • 33
  • 1
  • 1
  • 3

1 Answers1

3

A histogram works with a continuous x axis, as the error states. Your x-axis is on pclass, which is a factor (which R treats as discrete).

If you want to get a count by pclass type, you want a geom_bar instead:

ggplot(train, aes(x = pclass, fill = factor(survived))) +
    geom_bar(stat = "count") +
    xlab("pclass") +
    ylab("total count") +
    labs(fill = "survived")
Chris
  • 6,302
  • 1
  • 27
  • 54
  • Cheers, that solved my issue. I tried changing pclass earlier to and int as well but did not work. Thanks for the added information, much appreciated ! – Chris Kubik Feb 24 '17 at 11:55