forked from joseph-ProCogia/SAS-to-R-for-Medicine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ggplot examples.R
72 lines (52 loc) · 2 KB
/
ggplot examples.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#SAS to R - Introduction Course
#Introduction - ggplot examples
#ProCogia - Higher Intelligence. Deeper Insights. Smarter Decisions.
#reference library
library(tidyverse)
#load iris data from tidyverse
data(iris)
# Look at data
head(iris)
# Create basic simple scatter plot
ggplot(data=iris, aes(x=Sepal.Length, Sepal.Width)) + # initialize ggplot object
geom_point() # add scatter plot layer
# Color by Species
# map the color aesthetic to the variable Species within aes()
ggplot(data=iris, aes(x=Sepal.Length, Sepal.Width)) +
geom_point(aes(color=Species))
# Add title with ggtitle()
# customize axis labels
ggplot(data=iris, aes(x=Sepal.Length, Sepal.Width)) +
geom_point(aes(color=Species)) +
ggtitle("Sepal Width vs Sepal Length") +
xlab("Sepal length") + ylab("Sepal Width")
# Facetted by species
ggplot(data=iris, aes(x=Sepal.Length, Sepal.Width)) +
geom_point(aes(color=Species)) +
facet_wrap(~Species) +
ggtitle("Sepal Width vs Sepal Length") +
xlab("Sepal length") + ylab("Sepal Width")
## More examples with diamonds dataset
data(diamonds)
head(diamonds)
# bar chart
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill=cut))
# histogram
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = price), fill='blue')
# histogram, specify custom binwidth
# can use hex RGB values to customize fill color
ggplot(data = diamonds) +
geom_histogram(mapping = aes(x = price, fill=price), binwidth = 1000, fill="#42ddf5")
# continuous density estimate
ggplot(data = diamonds) +
geom_density(mapping = aes(x = price), fill="#42ddf5")
# boxplot
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = cut, y=price), fill="#42ddf5")
# boxplot, customize with transparency (alpha) and outlier display
ggplot(data = diamonds) +
geom_boxplot(mapping = aes(x = cut, y=price), fill="#42ddf5", alpha=0.4,
outlier.shape = 1, outlier.color='red', outlier.size = 0.2)