
How it works...
The recipe begins with a very simple step. It simply creates objects (color1, color2) to hold color names. By separating them, we ensure that the code becomes more readable. Also, let me stress that the selection of colors plays a very important role here. There are way more dots for males than there is for females. Picking darker colors for females and lighter ones for males will make these fewer observations much more visible.
This color selection is strategical as it makes easier to visualize female observations. Even for exploratory figures the color selection can play a very important role. A well made color selection do contribute to insights. It's a good thing to spend some time picking the right colors.
Next step creates the color vector (color_fill) and sorts it accordingly. As we want to color dots with respect to the sex variable, this vector's elements must be colors matching values coming from Salaries$sex. To create such a vector, the ifselse() function was used.
It gets a condition as the first argument, returning the second argument if the condition is meet, otherwise returning the third argument. The way it was designed, ifselse() is checking upon each value coming from Salaries' sex variable, returning color1 for 'Male' observations and color2 for 'Female'.
For variables with only two possible values, using a single ifelse() function may be be the easiest way to go. If there are three ore more possible values, many ifselse() functions can be chained to get a vector of colors. Alternatively,it's also possible to create a function to handle this task.
This step also reordered the color vector (color_fill). Skipping it wouldn't stop you from plotting, but if you check the data, the result would be very wrong. So don't you ever skip this step. The vector was reordered based on the x and y variables respectively. This is the same way geom_dotplot() reorders inputted data, color vector must obey this same order to fill the right dots.
Finally, step 4 reaches the dot plot. After drawing the basic aesthetic mappings under box1, geom_dotplot() is stacked to add the dot geometry. Aesthetics colour and fill are declared outside aes(). Object color_fill is fitting arguments.