Code
library(tidyverse)
library(gapminder)
library(ggpubr)
library(ggthemr)
library(ggplot2)
library(plotly)
library(magick)
packageVersion("ggplot2")
[1] '3.5.1'
Tony Duan
[1] '3.5.1'
total_bill tip sex smoker day time size
1 16.99 1.01 Female No Sun Dinner 2
2 10.34 1.66 Male No Sun Dinner 3
3 21.01 3.50 Male No Sun Dinner 3
4 23.68 3.31 Male No Sun Dinner 2
5 24.59 3.61 Female No Sun Dinner 4
6 25.29 4.71 Male No Sun Dinner 4
# A tibble: 6 × 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
1 Afghanistan Asia 1952 28.8 8425333 779.
2 Afghanistan Asia 1957 30.3 9240934 821.
3 Afghanistan Asia 1962 32.0 10267083 853.
4 Afghanistan Asia 1967 34.0 11537966 836.
5 Afghanistan Asia 1972 36.1 13079460 740.
6 Afghanistan Asia 1977 38.4 14880372 786.
` ::: {.cell}
:::
ggplot(data002, aes(x=reorder(continent,pop), y=pop,fill=factor(ifelse(continent=="Asia","Highlighted","Normal")))) +
geom_bar(stat="identity",alpha=0.2,show.legend = FALSE)+scale_fill_manual(name = "continent", values=c("red","grey50"))+coord_flip()+scale_y_continuous(expand = expansion(mult = c(0, .1)))
make 3 plot per row
remove scientific notation ::: {.cell}
:::
#pak::pak('thomasp85/gganimate')
library(gganimate)
p=ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
# Here comes the gganimate specific bits
# labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy',colour = "country") +
labs(title ='Year: {as.integer(frame_time)}', x = 'GDP per capita', y = 'life expectancy',colour = "country") +
transition_time(year) +
ease_aes('linear')
p
https://www.youtube.com/watch?v=efj6-aawubs&list=PLBnFxG6owe1FcJnrNbaIJyALHMyoKW27T
The goal of patchwork is to make it ridiculously simple to combine separate ggplots into the same graphic.
The goal of legendry is to provide additional guide functionality to the ggplot2 ecosystem.
# A partial guide to display a bracket
efficient_bracket <- primitive_bracket(
# Keys determine what is displayed
key = key_range_manual(start = 25, end = Inf, name = "Efficient"),
bracket = "square",
# We want vertical text
theme = theme(
legend.text = element_text(angle = 90, hjust = 0.5),
axis.text.y.left = element_text(angle = 90, hjust = 0.5)
)
)
base + guides(y = guide_axis_stack("axis", efficient_bracket))
https://cran.r-project.org/web/packages/magick/vignettes/intro.html
https://yutannihilation.github.io/allYourFigureAreBelongToUs/ggthemes/
---
title: "ggplot2 in R"
author: "Tony Duan"
execute:
warning: false
error: false
format:
html:
toc: true
toc-location: right
code-fold: show
code-tools: true
number-sections: true
code-block-bg: true
code-block-border-left: "#31BAE9"
code-copy: true
---
{width="800"}
```{r}
library(tidyverse)
library(gapminder)
library(ggpubr)
library(ggthemr)
library(ggplot2)
library(plotly)
library(magick)
packageVersion("ggplot2")
```
```{r}
library(reshape2)
tips=tips
head(tips)
```
```{r}
data001=gapminder
head(data001)
```
# Scatter Plot
```{r}
p=ggplot(tips, aes(tip, total_bill)) + geom_point()
p
```
## color by group
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()
p
```
## size by group
```{r}
p=ggplot(tips, aes(tip, total_bill,colour = sex,size=size)) + geom_point()
p
```
## line Plot
```{r}
data002= data001 %>% group_by(continent,year) %>% summarise(pop=sum(pop))
```
```{r}
p=ggplot(data002 %>%filter(continent=='Asia'), aes(year, pop)) + geom_line()
p
```
### change line size
```{r}
p=ggplot(data002 %>%filter(continent=='Asia'), aes(year, pop)) + geom_line(size=5)
p
```
## color by group
```{r}
p=ggplot(data002, aes(year, pop,colour = continent)) + geom_line()
p
```
# histogram
```{r}
data002= data001 %>% filter(year==1997,continent %in% c('Asia','Africa'))
```
```{r}
ggplot(data002, aes(gdpPercap)) +
geom_histogram()
```
## color by group
```{r}
ggplot(data002, aes(gdpPercap,,fill = continent)) +geom_histogram(position = 'dodge')
```
# bar chart
```{r}
data002= data001 %>% filter(year==1997) %>% group_by(continent) %>% summarise(pop=sum(pop))
```
```{r}
ggplot(data002, aes(x=continent, y=pop)) +
geom_bar(stat="identity")+scale_y_continuous(labels = scales::comma)
```
## show number
```{r}
ggplot(data002, aes(x=continent, y=pop)) +
geom_bar(stat="identity")+scale_y_continuous(labels = scales::comma)+geom_text(aes(label = pop), vjust = -0.2)
```
## change bar color
```{r}
ggplot(data002, aes(x=continent, y=pop)) +
geom_bar(stat="identity",fill='red')+scale_y_continuous(labels = scales::comma)+geom_text(aes(label = pop), vjust = -0.2)
# box plot
```
## bar plot order
```{r}
ggplot(data002, aes(x=reorder(continent,pop), y=pop)) +
geom_bar(stat="identity",fill='red')+scale_y_continuous(labels = scales::comma)+geom_text(aes(label = pop), vjust = -0.2)
# box plot
```
```{r}
ggplot(data002, aes(x=reorder(continent,-pop), y=pop)) +
geom_bar(stat="identity",fill='red')+scale_y_continuous(labels = scales::comma)+geom_text(aes(label = pop), vjust = -0.2)
# box plot
```
## Horizontal Barplot
`
```{r}
ggplot(data002, aes(x=reorder(continent,pop), y=pop)) +
geom_bar(stat="identity",fill='red')+scale_y_continuous(labels = scales::comma)+geom_text(aes(label = pop), vjust = -0.2)+coord_flip()
# box plot
```
## make bar transparency
```{r}
ggplot(data002, aes(x=reorder(continent,pop), y=pop)) +
geom_bar(stat="identity",fill='red' ,alpha=0.2)+coord_flip()
```
## make bar close to axis
```{r}
ggplot(data002, aes(x=reorder(continent,pop), y=pop)) +
geom_bar(stat="identity",alpha=0.2,fill='red')+coord_flip()+scale_y_continuous(expand = expansion(mult = c(0, .1)))
```
## change one bar color
```{r}
ggplot(data002, aes(x=reorder(continent,pop), y=pop,fill=factor(ifelse(continent=="Asia","Highlighted","Normal")))) +
geom_bar(stat="identity",alpha=0.2,show.legend = FALSE)+scale_fill_manual(name = "continent", values=c("red","grey50"))+coord_flip()+scale_y_continuous(expand = expansion(mult = c(0, .1)))
```
## color by group
# box plot
```{r}
p=ggplot(tips, aes(day,tip,fill=sex)) + geom_boxplot()
p
```
# strip plot
```{r}
p=ggplot(tips, aes(day,tip)) + geom_jitter()
p
```
## color by group
```{r}
p=ggplot(tips, aes(day,tip,color=sex)) + geom_jitter(position=position_jitterdodge())
p
```
# Facet plot
```{r}
p=ggplot(tips, aes(tip,total_bill,)) + geom_point(aes(color=sex)) + facet_wrap("day")
p
```
make 3 plot per row
```{r}
p=ggplot(tips, aes(tip,total_bill,)) + geom_point(aes(color=sex)) + facet_wrap("day",ncol = 3)
p
```
# title,size,x y name,footnote
## add title
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ ggtitle("tip by sex")
p
```
## add subtitle
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ ggtitle("tip by sex",subtitle = "Subtitle of the plot")
p
```
## add footnote
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ ggtitle("tip by sex")+labs(caption = "this is footnote")
p
```
## adjust plot size
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ ggtitle("tip by sex")+theme(
plot.margin = margin(2, 2, 5, 5, "cm"))
p
```
## adjust text size and center title
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ ggtitle("tip by sex")+labs(caption = "this is footnote")
p+theme(plot.title = element_text(hjust = 0.5),text = element_text(size = 30))
```
## change x y name
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+xlab("new x name") + ylab("new y name")
p
```
## add chinese
```{r}
library(showtext)
showtext_auto()
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ scale_x_continuous(name="新的 x name")+ scale_y_continuous(name="新的 y name")
p
```
## x y break and scales limit
### x scales limit
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ scale_x_continuous(name="new x name")+ scale_y_continuous(name="new y name")
p+ xlim(min=0, 20)
```
### y scales limit
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ scale_x_continuous(name="new x name")+ scale_y_continuous(name="new y name")
p+ ylim(0, 100)
```
### adding second aix
```{r}
data002= data001%>% group_by(year,continent) %>% summarise(pop=sum(pop),lifeExp=mean(lifeExp))%>%filter(continent=='Asia')
```
remove scientific notation
```{r}
coeff=1/40000000
p=ggplot(data002, aes(year, pop)) + geom_col() +
geom_line(aes(year,lifeExp/ coeff),size=2, color = "red") +scale_y_continuous("pop", sec.axis = sec_axis(~.*coeff, name = "lifeExp"),labels = scales::comma)
p
```
# applying themes
::: {.panel-tabset .nav-pills}
## theme_bw()
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ scale_x_continuous(name="new x name")+ scale_y_continuous(name="new y name")
p+ theme_bw()
```
## theme_light()
```{r}
p+ theme_light()
```
## theme_economist()
```{r}
library("ggthemes")
p+ theme_economist()
```
## theme_tufte()
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ scale_x_continuous(name="new x name")+ scale_y_continuous(name="new y name")
p+ theme_tufte()
```
## theme_wsj()
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ scale_x_continuous(name="new x name")+ scale_y_continuous(name="new y name")
p+ theme_wsj()
```
## theme_fivethirtyeight()
```{r}
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ scale_x_continuous(name="new x name")+ scale_y_continuous(name="new y name")
p+ theme_fivethirtyeight()
```
:::
# convert ggplot to plotly
```{r}
p=ggplot(data=tips, aes(tip, total_bill,color=sex)) + geom_point()+ scale_x_continuous(name="new x name")+ scale_y_continuous(name="new y name")
pp=ggplotly(p)
pp
```
# Save plot
```{r}
p+ theme_economist()
ggsave("myplot.png")
```
# add image into the chart
## add logo
```{r}
# Add your company's logo to the graph you created
logo <- image_read("logo.png")
p
grid::grid.raster(logo, x = 0.1, y = 0, just = c('left', 'bottom'), width = unit(0.4, 'inches'))
```
## add background image
```{r}
img4=image_read("bee.png")
"bee.png"
p=ggplot(tips, aes(tip, total_bill,color=sex)) + background_image(img4) +geom_point()+ scale_x_continuous(name="new x name")+ scale_y_continuous(name="new y name")
p
```
# Animation plot
```{r}
#pak::pak('thomasp85/gganimate')
library(gganimate)
p=ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
# Here comes the gganimate specific bits
# labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy',colour = "country") +
labs(title ='Year: {as.integer(frame_time)}', x = 'GDP per capita', y = 'life expectancy',colour = "country") +
transition_time(year) +
ease_aes('linear')
p
```
# ggplot2 extension packages
https://www.youtube.com/watch?v=efj6-aawubs&list=PLBnFxG6owe1FcJnrNbaIJyALHMyoKW27T
## patchwork
The goal of patchwork is to make it ridiculously simple to combine separate ggplots into the same graphic.
```{r}
#pak::pak('patchwork')
```
```{r}
library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
p4 <- ggplot(mtcars) + geom_bar(aes(carb))
(p1 | p2 | p3) /
p4
```
## legendry
The goal of legendry is to provide additional guide functionality to the ggplot2 ecosystem.
```{r}
#pak::pak('legendry')
```
```{r}
library(ggplot2)
library(legendry)
```
```{r}
base <- ggplot(mpg, aes(displ, hwy, colour = cty)) +
geom_point() +
labs(
x = "Engine displacement",
y = "Highway miles per gallon",
col = "City miles\nper gallon"
) +
theme(axis.line = element_line())
```
```{r}
# A partial guide to display a bracket
efficient_bracket <- primitive_bracket(
# Keys determine what is displayed
key = key_range_manual(start = 25, end = Inf, name = "Efficient"),
bracket = "square",
# We want vertical text
theme = theme(
legend.text = element_text(angle = 90, hjust = 0.5),
axis.text.y.left = element_text(angle = 90, hjust = 0.5)
)
)
base + guides(y = guide_axis_stack("axis", efficient_bracket))
```
## marquee
## ggiraph
## geomtextpath
## ggpattern
## ggbump
## gghighlight
## ggdist
# reference:
https://cran.r-project.org/web/packages/magick/vignettes/intro.html
https://yutannihilation.github.io/allYourFigureAreBelongToUs/ggthemes/