## ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics
library(ggplot2)
?ggplot2## starting httpd help server ... done
## Classes 'tbl_df', 'tbl' and 'data.frame': 1704 obs. of 6 variables:
## $ country : Factor w/ 142 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ continent: Factor w/ 5 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...
## $ year : int 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
## $ lifeExp : num 28.8 30.3 32 34 36.1 ...
## $ pop : int 8425333 9240934 10267083 11537966 13079460 14880372 12881816 13867957 16317921 22227415 ...
## $ gdpPercap: num 779 821 853 836 740 ...
## Def. gap
gap <- gapminder
## draw ggplot with x-axis(lifeExp)
ggplot(data = gap, aes(x = lifeExp))## draw ggplot with x-axis(lifeExp) and histogram
ggplot(data = gap, aes(x = lifeExp)) +
geom_histogram()## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## draw ggplot fill the blue color ,add the title,label of x-axis and label of y-axis
ggplot(data = gap, aes(x = lifeExp)) +
geom_histogram(fill = "blue", color = "black", bins = 10) +
ggtitle("Life expectancy for the gap dataset") +
xlab("Life expectancy (years)") +
ylab("Frequency") +
theme_classic() ##draw boxplot,Setting x = continent,y = lifeExp,add the title"Boxplots for lifeExp by continent",label of x-axis and label of y-axis
ggplot(data = gap, aes(x = continent, y = lifeExp, fill = continent)) +
geom_boxplot() +
ggtitle("Boxplots for lifeExp by continent") +
xlab("Continent") +
ylab("Life expectancy (years)") +
theme_minimal() +
guides(fill = FALSE) # What happens if you un-hashtage `guides(fill = FALSE)` and the plus sign in lines 68 and 69 above?
##try it
ggplot(data = gap, aes(x = continent, y = lifeExp, fill = continent)) +
geom_boxplot() +
ggtitle("Boxplots for lifeExp by continent") +
xlab("Continent") +
ylab("Life expectancy (years)") +
theme_minimal() ##we can see differnt of the two plot,the right continent will apeear or disappear
## Def. x,y. Use continent to display different color &shape.
##Add the point, adjust the size and translucence.
##Setting the tittle and label of x,y-axis.
##Move theme to the top.Setting tittle size=10,text size=5.
##Finally,adjust the angle and postition with x-axis's scale
ggplot(data = gap, aes(x = lifeExp, y = gdpPercap, color = continent, shape = continent)) +
geom_point(size = 5, alpha = 0.5) +
theme_classic() +
ggtitle("Scatterplot of life expectancy by gdpPercap") +
xlab("Life expectancy (years)") +
ylab("gdpPercap (USD)") +
theme(legend.position = "top",
plot.title = element_text(hjust = 0.5, size = 20),
legend.title = element_text(size = 10),
legend.text = element_text(size = 5),
axis.text.x = element_text(angle = 45, hjust = 1))