Author

Tony Duan

Code
library(tidyverse)
library(gapminder)
library(ggpubr)
library(ggthemr)

library(ggplot2)
library(plotly)

library(magick)
packageVersion("ggplot2")
[1] '3.5.1'
Code
library(reshape2)
tips=tips
head(tips)
  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
Code
data001=gapminder
head(data001)
# 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.

1 Scatter Plot

Code
p=ggplot(tips, aes(tip, total_bill)) + geom_point()
p

1.1 color by group

Code
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()
p

1.2 size by group

Code
p=ggplot(tips, aes(tip, total_bill,colour = sex,size=size)) + geom_point()
p

1.3 line Plot

Code
data002= data001 %>% group_by(continent,year) %>% summarise(pop=sum(pop))
Code
p=ggplot(data002 %>%filter(continent=='Asia'), aes(year, pop)) + geom_line()
p

1.3.1 change line size

Code
p=ggplot(data002 %>%filter(continent=='Asia'), aes(year, pop)) + geom_line(size=5)
p

1.4 color by group

Code
p=ggplot(data002, aes(year, pop,colour = continent)) + geom_line()
p

2 histogram

Code
data002= data001 %>% filter(year==1997,continent %in% c('Asia','Africa'))
Code
ggplot(data002, aes(gdpPercap)) + 
  geom_histogram()

2.1 color by group

Code
ggplot(data002, aes(gdpPercap,,fill = continent)) +geom_histogram(position = 'dodge')

3 bar chart

Code
data002= data001 %>% filter(year==1997) %>% group_by(continent) %>% summarise(pop=sum(pop))
Code
ggplot(data002, aes(x=continent, y=pop)) +
  geom_bar(stat="identity")+scale_y_continuous(labels = scales::comma)

3.1 show number

Code
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)

3.2 change bar color

Code
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)

Code
# box plot

3.3 bar plot order

Code
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)

Code
# box plot
Code
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)

Code
# box plot

3.4 Horizontal Barplot

` ::: {.cell}

Code
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()

Code
# box plot

:::

3.5 make bar transparency

Code
ggplot(data002, aes(x=reorder(continent,pop), y=pop)) +
  geom_bar(stat="identity",fill='red' ,alpha=0.2)+coord_flip()

3.6 make bar close to axis

Code
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)))

3.7 change one bar color

Code
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)))

3.8 color by group

4 box plot

Code
p=ggplot(tips, aes(day,tip,fill=sex)) + geom_boxplot()
p

5 strip plot

Code
p=ggplot(tips, aes(day,tip)) + geom_jitter()
p

5.1 color by group

Code
p=ggplot(tips, aes(day,tip,color=sex)) + geom_jitter(position=position_jitterdodge())
p

6 Facet plot

Code
p=ggplot(tips, aes(tip,total_bill,)) + geom_point(aes(color=sex)) + facet_wrap("day")
p

make 3 plot per row

Code
p=ggplot(tips, aes(tip,total_bill,)) + geom_point(aes(color=sex)) + facet_wrap("day",ncol = 3)
p

7 title,size,x y name,footnote

7.1 add title

Code
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ ggtitle("tip by sex")
p

7.2 add subtitle

Code
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ ggtitle("tip by sex",subtitle = "Subtitle of the plot")
p

7.3 add footnote

Code
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+ ggtitle("tip by sex")+labs(caption = "this is footnote")
p

7.4 adjust plot size

Code
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

7.5 adjust text size and center title

Code
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))

7.6 change x y name

Code
p=ggplot(tips, aes(tip, total_bill,color=sex)) + geom_point()+xlab("new x name") + ylab("new y name")
p

7.7 add chinese

Code
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

7.8 x y break and scales limit

7.8.1 x scales limit

Code
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)

7.8.2 y scales limit

Code
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)

7.8.3 adding second aix

Code
data002= data001%>% group_by(year,continent) %>% summarise(pop=sum(pop),lifeExp=mean(lifeExp))%>%filter(continent=='Asia')

remove scientific notation ::: {.cell}

Code
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

:::

8 applying themes

9 convert ggplot to plotly

Code
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

10 Save plot

Code
p+ theme_economist()

Code
ggsave("myplot.png")

11 add image into the chart

11.2 add background image

Code
img4=image_read("bee.png")

"bee.png"
[1] "bee.png"
Code
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

12 Animation plot

Code
#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

13 ggplot2 extension packages

https://www.youtube.com/watch?v=efj6-aawubs&list=PLBnFxG6owe1FcJnrNbaIJyALHMyoKW27T

13.1 patchwork

The goal of patchwork is to make it ridiculously simple to combine separate ggplots into the same graphic.

Code
#pak::pak('patchwork')
Code
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

13.2 legendry

The goal of legendry is to provide additional guide functionality to the ggplot2 ecosystem.

Code
#pak::pak('legendry')
Code
library(ggplot2)
library(legendry)
Code
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())
Code
# 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))

13.3 marquee

13.4 ggiraph

13.5 geomtextpath

13.6 ggpattern

13.7 ggbump

13.8 gghighlight

13.9 ggdist

14 reference:

https://cran.r-project.org/web/packages/magick/vignettes/intro.html

https://yutannihilation.github.io/allYourFigureAreBelongToUs/ggthemes/

Back to top