12.07.2015 Views

R dummies

R dummies

R dummies

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Working with scalesIn ggplot2, scales control the way your data gets mapped to your geom. Inthis way, your data is mapped to something you can see (for example, lines,points, colors, position, or shapes).The ggplot2 package is extremely good at selecting sensible default valuesfor your scales. In most cases, you don’t have to do much to customize yourscales. However, ggplot2 has a wide range of very sophisticated functionsand settings to give you fine-grained control over your scale behavior andappearance.In the following example, you map the column mtcars$cyl to both the shapeand color of the points. This creates two separate, but overlapping, scales:One scale controls shape, while the second scale controls the color of thepoints:> ggplot(mtcars, aes(x=hp, y=mpg)) ++ geom_point(aes(shape=factor(cyl),colour=factor(cyl)))The name of a scale defaults to the name of the variable that gets mappedto it. In this case, you map factor(cyl) to the scale. To change theappearance of a scale, you need to add a scale function to your plot. Thespecific scale function you use is dependent on the type of scale, but in thiscase, you have a shape scale with discrete values, so you use thescale_shape_ discrete() function. You also have a color scale with discretevalue, so you can control that with scale_colour_discrete(). To change thename that appears in the legend of the plot, you need to specify theargument name to these scales. For example, change the name of the legendto “Cylinders” by setting the argument name=”Cylinders”:> ggplot(mtcars, aes(x=hp, y=mpg)) ++ geom_point(aes(shape=factor(cyl),colour=factor(cyl))) ++ scale_shape_discrete(name=”Cylinders”) ++ scale_colour_discrete(name=”Cylinders”)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!