Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
R in Action, Second Edition.pdf
Скачиваний:
540
Добавлен:
26.03.2016
Размер:
20.33 Mб
Скачать

462

CHAPTER 19 Advanced graphics with ggplot2

Note the difference between faceting and multiple graphs. Faceting creates an array of plots based on one or more categorical variables. In this section, you’re arranging completely independent plots into a single graph.

19.8 Saving graphs

You can save the graphs created by ggplot2 using the standard methods discussed in section 1.3.4. But a convenience function named ggsave() can be particularly useful. Options include which plot to save, where to save it, and in what format. For example,

myplot <- ggplot(data=mtcars, aes(x=mpg)) + geom_histogram() ggsave(file="mygraph.png", plot=myplot, width=5, height=4)

saves myplot as a 5-inch by 4-inch PNG file named mygraph.png in the current working directory. You can save the graph in a different format by setting the file extension to ps, tex, jpeg, pdf, jpeg, tiff, png, bmp, svg, or wmf. The wmf format is only available on Windows machines.

If you omit the plot= option, the most recently created graph is saved. The code

ggplot(data=mtcars, aes(x=mpg)) + geom_histogram() ggsave(file="mygraph.pdf")

is valid and saves the graph to disk. See help(ggsave) for additional details.

19.9 Summary

This chapter reviewed the ggplot2 package, which provides advanced graphical methods based on a comprehensive grammar of graphics. The package is designed to provide you with a complete and comprehensive alternative to the native graphics provided with R. It offers methods for creating attractive and meaningful visualizations of data that are difficult to generate in other ways.

The ggplot2 package can be difficult to learn, but a wealth of material is available to help you on your journey (I promised myself that I would never use that word, but learning ggplot2 can certainly feel like one). A list of all ggplot2 functions, along with examples, can be found at http://docs.ggplot2.org. To learn about the theory underlying ggplot2, see the original book by Wickham (2009). Finally, Chang (2013) has written a very practical book, chock full of useful examples. Chang’s book is definitely where I would start.

You should now have a firm grasp of the many ways that R allows you to create visual representations of data. If a picture is worth a thousand words, and R provides a thousand ways to create a picture, then R must be worth a million words (or something to that effect). In the next chapter two chapters, you’ll delve deeper into R as a programming language.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]