0

I want to add a year segment to clearly visualize each year category but failed to use if statement in it. Is it possible to use if in ggplot? If not, is there any better way to visualize it. Thanks.

enter image description here

enter image description here

benson23
  • 16,369
  • 9
  • 19
  • 38
DAVID LEE
  • 11
  • 3
  • 3
    There are several things that appear wrong to my eye. 1) you're using `year_of_birth` in your `if` statements as if it is a global variable, whereas it is a column in a dataframe (presumably). 2) You're trying to do a numerical comparison with character variables in e.g. `... < '1970'` instead of `... < 1970`. 3) I don't understand what you're trying to do by adding a print statement to a plot, I've never seen this. – teunbrand Mar 02 '22 at 15:21
  • 3
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Please don't post code or data as images because we cannot copy/pastes that for testing. Note that `5 < x <10` is not valid syntax in R. You need something like `5 < x & x < 10` – MrFlick Mar 02 '22 at 15:21
  • As a general suggestion - I don't know the R code for this: A possible workaround could be to remove the year-of-birth labels from the x axis, and instead put in your three wanted texts as text elements. I have worked in Stata, where one can position text in a graph in several ways according to whether it is a text box, a legend, a note etc. I would expect ggplot to have similar possibilities, to position your texts where you want them. – Steinar Bjørnæs Mar 02 '22 at 16:19
  • OP, it looks like your `year_of_birth` column data is composed of characters, and is not numeric - is this correct? – chemdork123 Mar 04 '22 at 02:59
  • thank you everyone for contributing wisdom to this, I am new to Stack Overflow and a beginner in R, I am sure my code chunk could be way out of the professional league. I'll try to formalise my writings here in the future, and clarify my question as much as I can. In the above, I just want to visualise by different year period, and I just somehow don't know how to write them. Maybe I should focus on basic skill improvement rather than dive into EDA immdediately? – DAVID LEE Mar 23 '22 at 06:13

0 Answers0