1.1 绘制基本图形

1.1.1 散点图

pacman::p_load(tidyverse)
diamonds %>% 
  ggplot(aes(carat,price))->gg

gg + geom_point()
gg + geom_point(stroke=2) # # 'stroke' controls the thickness of point boundary

1.1.2 静态点的尺寸、形状、颜色和边界厚度

gg + geom_point(size = 1,shape = 1,color = "steelblue",stroke = 2)

1.1.3 动态点的大小、形状、颜色和边界厚度

gg + geom_point(aes(size = carat,shape = cut,color = color,stroke = carat))
## Warning: Using shapes for an ordinal variable is not advised

1.1.4 添加标题、X轴和Y轴标签

gg +
  geom_point(aes(col = color))->gg1
gg1 + 
  labs(title = "Diamonds",x = "Carat",y = "Price") +
  theme(plot.title = element_text(size = 15,hjust = 0.5),
        axis.title = element_text(size = 12),
        axis.text = element_text(size = 10))->gg2
gg2

1.1.5 更改所有文本的颜色

gg2 + theme(text = element_text(colour = "blue"))

1.1.6 更改标题、X轴和Y轴标签和文本大小

  • plot.title: Controls plot title.
  • axis.title.x: Controls X axis title
  • axis.title.y: Controls Y axis title
  • axis.text.x: Controls X axis text
  • axis.text.y: Controls y axis text
gg3 <- gg2 + theme(plot.title=element_text(size=15), 
                   axis.title.x=element_text(size=12), 
                   axis.title.y=element_text(size=12), 
                   axis.text.x=element_text(size=10), 
                   axis.text.y=element_text(size=10))
print(gg3)

1.1.7 改变标题面,颜色,线条高度

gg3 + 
  labs(title = "Plot Title\nSecond Line of Plot Title") +
  theme(plot.title = element_text(face = "bold",color = "steelblue",lineheight=1))

1.1.8 改变点的颜色

gg3 + 
  scale_colour_manual(name='Legend', 
                      values=c('D'='grey', 
                               'E'='red', 
                               'F'='blue', 
                               'G'='yellow',
                               'H'='black', 
                               'I'='green', 
                               'J'='firebrick'))
gg3 + scale_color_brewer(palette = "Set3")

1.1.9 调整X轴和Y轴范围

方法一:Zoom in

gg3 +
  coord_cartesian(xlim=c(0,3), ylim=c(0, 5000)) + 
  geom_smooth()  # zoom in
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

方法二:Deletes the points outside limits

gg3 + 
  xlim(c(0,3))+
  ylim(c(0, 5000)) +
  geom_smooth()  # deletes the points 
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
## Warning: Removed 14714 rows containing non-finite values (stat_smooth).
## Warning: Removed 14714 rows containing missing values (geom_point).

方法三:Deletes the points outside limits

gg3 + geom_smooth()
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
gg3 +
  scale_x_continuous(limits = c(0,3))+
  scale_y_continuous(limits = c(0,5000)) +
  geom_smooth()
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
## Warning: Removed 14714 rows containing non-finite values (stat_smooth).
## Warning: Removed 14714 rows containing missing values (geom_point).

1.1.10 更改X轴和Y轴标签

gg3
gg3 + 
  scale_x_continuous(labels = c("zero", "one", "two", "three", "four", "five")) +
  scale_y_continuous(breaks=seq(0, 20000, 4000),labels = str_c(seq(0,20,4),"K"))

1.1.11 旋转轴文本

gg3 + 
  theme(axis.text = element_text(angle = 45))

1.1.12 翻转X轴和Y轴

gg3 
gg3 + coord_flip()->gg3_flip
gridExtra::grid.arrange(gg3,gg3_flip,ncol = 2)

1.1.13 网格线和面板背景

gg3 + 
  theme(panel.background = element_rect(fill = 'springgreen'),
  panel.grid.major = element_line(colour = "firebrick", size=3),
  panel.grid.minor = element_line(colour = "blue", size=1))

1.1.14 绘制图边缘和背景

gg3 + 
  theme(plot.background=element_rect(fill="yellowgreen"), 
        plot.margin = unit(c(2, 4, 1, 3), "cm"))->gg3_background # top, right, bottom, left

gridExtra::grid.arrange(gg3,gg3_background,ncol = 2)

1.1.15 设置颜色

使用colors()函数会在R控制台中显示所有的颜色。以下是我对好看的颜色和背景的一些建议:

  • steelblue (points and lines)
  • firebrick (point and lines)
  • springgreen (fills)
  • violetred (fills)
  • tomato (fills)
  • skyblue (bg)
  • sienna (points, lines)
  • slateblue (fills)
  • seagreen (points, lines, fills)
  • sandybrown (fills)
  • salmon (fills)
  • saddlebrown (lines)
  • royalblue (fills)
  • orangered (point, lines, fills)
  • olivedrab (points, lines, fills)
  • midnightblue (lines)
  • mediumvioletred (points, lines, fills)
  • maroon (points, lines, fills)
  • limegreen (fills)
  • lawngreen (fills)
  • forestgreen (lines, fills)
  • dodgerblue (fills, bg)
  • dimgray (grids, secondary bg)
  • deeppink (fills)
  • darkred (lines, points)

If you are looking for consistent colors, the RColorBrewer package has predefined color palettes

1.2 图例

1.2.1 隐藏图例

gg3 + 
  theme(legend.position="none")  # hides the legend

1.2.2 改变图例标题

gg3 + scale_color_discrete(name = "")

gg3 +
  theme(legend.title = element_blank())->p1
gg3 + 
  scale_color_discrete(name = "Diamonds")->p2
library(gridExtra)
## 
## Attaching package: 'gridExtra'
## The following object is masked from 'package:dplyr':
## 
##     combine
grid.arrange(p1,p2,ncol = 2)

1.2.3 改变图例和点的颜色

gg3 +
  scale_color_manual(name = "Legend",
                     values = c('D'='grey', 
                                'E'='red', 
                                'F'='blue',
                                'G'='yellow', 
                                'H'='black', 
                                'I'='green', 
                                'J'='firebrick'))

1.2.4 改变图例位置

gg3 + 
  theme(legend.position = "top")->p1

p2 <- gg3 + 
  theme(legend.justification=c(1,0), legend.position=c(1,0))  # legend justification is the anchor point on the legend, considering the bottom left of legend as (0,0)
gridExtra::grid.arrange(p1, p2, ncol=2)

1.2.5 更改图例项的顺序

在图例中创建一个新的因子变量,按需要排序。然后在图中使用这个变量。

df$newLegendColumn <- factor(df$legendcolumn, 
                             levels=c(new_order_of_legend_items), 
                             ordered = TRUE) 

Legend title, text, box, symbol

  • legend.title - Change legend title
  • legend.text - Change legend text
  • legend.key - Change legend box
  • guides - Change legend symbols
gg3 + 
  scale_color_discrete(name = "Color") +
  theme(legend.title = element_text(size=15, color = "firebrick"), 
        legend.text = element_text(size=12), 
        legend.key=element_rect(fill='steelblue')) +
        guides(colour =  guide_legend(override.aes = list(size=2, shape=4, stroke=2)))  # legend title color and size, box color, symbol color, size and shape.

knitr::include_graphics("symbols.png")

1.3 图文本和注释

1.3.1 在图中添加文本

#> Not Run: gg + geom_text(aes(xcol, ycol, label=round(labelCol), size=3))  # general format
gg +
  geom_point()
diamonds$color %>% fct_count()
## # A tibble: 7 x 2
##   f         n
##   <fct> <int>
## 1 D      6775
## 2 E      9797
## 3 F      9542
## 4 G     11292
## 5 H      8304
## 6 I      5422
## 7 J      2808
gg + 
  geom_text(aes(label=color, color=color), size=4) +
  theme(plot.title = element_text(hjust = 0.5,size = 15),
        axis.title = element_text(size = 12),
        text = element_text(colour = "blue")) +
  scale_color_discrete(name = "Color") +
  labs(x = "Carat",y = "Price",title = "Diamonds")

1.3.2 注释

#> gg3 + annotate("mytext", x=xpos, y=ypos, label="My text")  # Not run: General Format
library(grid)
my_grob <- grobTree(textGrob("My Custom Text", x=0.5, y=0.2, gp=gpar(col="firebrick",fontsize=20, fontface="bold")))
gg3 + annotation_custom(my_grob)

1.4 绘制多个图

1.4.1 多个表版

gg1 + 
  facet_grid(color~cut)->p1
p1

1.4.2 X轴和Y轴自由缩放

Free X and Y axis scales

By setting scales='free', the scales of both X and Y axis is freed. Use scales='free_x' to free only X-axis and scales='free_y' to free only Y-axis.

p1 + facet_wrap(color~cut,scales = "free")->p2
p2

1.4.3 排列多个图形

grid.arrange(p1,p2,ncol = 2)

1.5 几何图层

1.5.1 添加平滑线

gg3 + 
  geom_smooth(aes(col = color)) +
  scale_color_brewer(palette = "Set1")
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'

1.5.2 添加水平和垂直线

gg3 +
  geom_hline(yintercept = 5000,size = 2,linetype = "dotted",col = "blue")->p1# linetypes: solid, dashed, dotted, dotdash, longdash and twodash
p2 <- gg3 + 
  geom_vline(xintercept=4, size=2, color="firebrick")

p3 <- 
  gg3 + 
  geom_segment(aes(x=4, y=5000, xend=5, yend=10000),lineend = "round",size=2) +
  scale_linetype_discrete()

p4 <- 
  gg3 +
  geom_segment(aes(x=carat, y=price, xend=carat, yend=price-500, color=color), size=2) + 
  coord_cartesian(xlim=c(2, 5))  # x, y: start points. xend, yend: end points

gridExtra::grid.arrange(p1,p2,p3,p4, ncol=2)

1.5.3 添加条形图

# Frequency bar chart: Specify only X axis.
mtcars %>% glimpse()
## Observations: 32
## Variables: 11
## $ mpg  <dbl> 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.2, 17...
## $ cyl  <dbl> 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4,...
## $ disp <dbl> 160.0, 160.0, 108.0, 258.0, 360.0, 225.0, 360.0, 146.7, 140.8,...
## $ hp   <dbl> 110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, 180, ...
## $ drat <dbl> 3.90, 3.90, 3.85, 3.08, 3.15, 2.76, 3.21, 3.69, 3.92, 3.92, 3....
## $ wt   <dbl> 2.620, 2.875, 2.320, 3.215, 3.440, 3.460, 3.570, 3.190, 3.150,...
## $ qsec <dbl> 16.46, 17.02, 18.61, 19.44, 17.02, 20.22, 15.84, 20.00, 22.90,...
## $ vs   <dbl> 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,...
## $ am   <dbl> 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0,...
## $ gear <dbl> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4, 3,...
## $ carb <dbl> 4, 4, 1, 1, 2, 1, 4, 2, 2, 4, 4, 3, 3, 3, 4, 4, 4, 1, 2, 1, 1,...
gg <- ggplot(mtcars,aes(x = cyl %>% as_factor() %>% fct_inorder())) +
  labs(x = "cyl")
gg +
  geom_bar()

gg +
  geom_bar(aes(fill = factor(vs)),position = "dodge")->p1

gg +
  geom_bar(aes(fill = factor(vs)),position = "fill")->p2

gg +
  geom_bar(aes(fill = factor(vs)),position = "stack")->p3

gg +
  geom_bar(aes(fill = factor(vs)))->p4

grid.arrange(p1,p2,p3,p4)

# Absolute bar chart: Specify both X adn Y axis. Set stat="identity"
mtcars %>% 
  group_by(cyl) %>% 
  summarise(mean(mpg)) %>% 
  rename(mpg = `mean(mpg)`)->df

df
## # A tibble: 3 x 2
##     cyl   mpg
##   <dbl> <dbl>
## 1     4  26.7
## 2     6  19.7
## 3     8  15.1
gg_bar <- ggplot(df, aes(x=cyl, y=mpg)) + 
  geom_bar(stat = "identity")  # Y axis is explicit. 'stat=identity'

print(gg_bar)

1.5.4 条形图绘制离散颜色

gg_bar <- df %>% 
  ggplot(aes(cyl,mpg)) +
  geom_bar(stat = "identity",aes(fill = cyl))

gg_bar

1.5.5 改变条形图颜色和宽度

df$cyl <- factor(df$cyl)
df %>% 
  ggplot(aes(cyl,mpg)) +
  geom_bar(stat = "identity",aes(fill = cyl),width = 0.25) +
  scale_fill_manual(name = "Cyl",
                    values=c("4"="steelblue", "6"="firebrick", "8"="darkgreen"))

1.5.6 改变颜色调色板

library(RColorBrewer)
RColorBrewer::brewer.pal.info
##          maxcolors category colorblind
## BrBG            11      div       TRUE
## PiYG            11      div       TRUE
## PRGn            11      div       TRUE
## PuOr            11      div       TRUE
## RdBu            11      div       TRUE
## RdGy            11      div      FALSE
## RdYlBu          11      div       TRUE
## RdYlGn          11      div      FALSE
## Spectral        11      div      FALSE
## Accent           8     qual      FALSE
## Dark2            8     qual       TRUE
## Paired          12     qual       TRUE
## Pastel1          9     qual      FALSE
## Pastel2          8     qual      FALSE
## Set1             9     qual      FALSE
## Set2             8     qual       TRUE
## Set3            12     qual      FALSE
## Blues            9      seq       TRUE
## BuGn             9      seq       TRUE
## BuPu             9      seq       TRUE
## GnBu             9      seq       TRUE
## Greens           9      seq       TRUE
## Greys            9      seq       TRUE
## Oranges          9      seq       TRUE
## OrRd             9      seq       TRUE
## PuBu             9      seq       TRUE
## PuBuGn           9      seq       TRUE
## PuRd             9      seq       TRUE
## Purples          9      seq       TRUE
## RdPu             9      seq       TRUE
## Reds             9      seq       TRUE
## YlGn             9      seq       TRUE
## YlGnBu           9      seq       TRUE
## YlOrBr           9      seq       TRUE
## YlOrRd           9      seq       TRUE
display.brewer.all(exact.n=TRUE)  # display available color palettes

ggplot(mtcars, aes(x=cyl, y=carb, fill=factor(cyl))) + 
  geom_bar(stat="identity") +
  scale_fill_brewer(palette="Set2",name = "Cyl")# "Reds" is palette name

1.5.7 折线图

方法一:

economics %>% 
  ggplot(aes(x = date)) +
  geom_line(aes(y = psavert),size = 2,col = "firebrick") +
  geom_line(aes(y  = uempmed),size = 1,col ="steelblue",linetype = "twodash") # available linetypes: solid, dashed, dotted, dotdash, longdash and twodash

方法二:

economics %>% 
  select(date,psavert,uempmed) %>% 
  tidyr::gather(key = variable,value = value,-date) %>% 
  ggplot(aes(x = date,y = value,col = variable)) +
  geom_line() +
  scale_x_date(date_breaks = "2 year") +
  theme(axis.text.x = element_text(size = 10,angle = 45,hjust = 1,vjust = 1))

1.5.8 时间序列折线图

pacman::p_load(ggfortify)
autoplot(AirPassengers, size=1) + 
  labs(title="AirPassengers") +
  scale_x_date(date_breaks = "1 year",expand = c(0,0)) +
  theme(axis.text.x = element_text(size = 10,angle = 45,hjust = 1,vjust = 1)) +
  scale_y_continuous(expand = c(0,0))
## Scale for 'y' is already present. Adding another scale for 'y', which will
## replace the existing scale.

1.5.9 色带

# Prepare the dataframe
st_year <- start(AirPassengers)[1]

st_month <- "01"

st_date <- as.Date(paste(st_year, st_month, "01", sep="-"))

dates <- seq.Date(st_date, length=length(AirPassengers), by="month")
df <- data.frame(dates, AirPassengers, AirPassengers/2)
head(df)
##        dates AirPassengers AirPassengers.2
## 1 1949-01-01           112            56.0
## 2 1949-02-01           118            59.0
## 3 1949-03-01           132            66.0
## 4 1949-04-01           129            64.5
## 5 1949-05-01           121            60.5
## 6 1949-06-01           135            67.5
gg <- ggplot(df, aes(x=dates)) +
  labs(title="AirPassengers") + 
  theme(plot.title=element_text(size=30,hjust = 0.5), 
        axis.title.x=element_text(size=20), 
        axis.text.x=element_text(size=10))

gg + geom_ribbon(aes(ymin=0, ymax=AirPassengers)) +
  geom_ribbon(aes(ymin=0, ymax=AirPassengers.2), fill="green") 

gg + geom_ribbon(aes(ymin=AirPassengers-20, ymax=AirPassengers+20)) +
  geom_ribbon(aes(ymin=AirPassengers.2-20, ymax=AirPassengers.2+20), fill="green")
## Don't know how to automatically pick scale for object of type ts. Defaulting to continuous.

1.5.10 面积图

除了ymin设置为0之外,geom_areageom_ribbon类似。如果你想让重叠的区域绘图,使用alpha唯美使顶层半透明。

economics %>% 
  select(date,psavert,uempmed) %>% 
  gather(key = variable, value = value,-date) %>% 
  ggplot(aes(x = date)) +
  geom_area(aes(y = value,fill = variable,col = variable)) +
  labs(title="Non-Overlapping - psavert and uempmed") +
  scale_x_date(date_breaks = "2 year",expand = c(0,0)) +
  scale_y_continuous(expand = c(0,0)) +
  theme(axis.text.x = element_text(hjust = 1,angle = 45,vjust = 1)) ->p1

p2 <- ggplot(economics, aes(x=date)) + 
  geom_area(aes(y=psavert), fill="yellowgreen", color="yellowgreen") + 
  geom_area(aes(y=uempmed), fill="dodgerblue", alpha=0.7, linetype="dotted") + 
  labs(title="Overlapping - psavert and uempmed") +
  scale_x_date(date_breaks = "2 year",expand = c(0,0)) +
  scale_y_continuous(expand = c(0,0)) +
  theme(axis.text.x = element_text(hjust = 1,angle = 45,vjust = 1))
  
gridExtra::grid.arrange(p1, p2, ncol=2)

1.5.11 箱线图和小提琴图

mtcars %>% 
  ggplot(aes(x = factor(cyl),mpg)) +
  geom_boxplot(aes(fill = factor(cyl)),
               width=0.5, 
               outlier.colour = "dodgerblue", 
               outlier.size = 1, 
               outlier.shape = 16, 
               outlier.stroke = 1, 
               notch=T) + 
  labs(title="Box plot")->p1

ggplot(mtcars, aes(factor(cyl), mpg)) + 
  geom_violin(aes(fill = factor(cyl)), width=0.5, trim=F) + 
  labs(title="Violin plot (untrimmed)")->p2  # violin plot

gridExtra::grid.arrange(p1, p2, ncol=2)
## notch went outside hinges. Try setting notch=FALSE.
## notch went outside hinges. Try setting notch=FALSE.

1.5.12 密度图

mtcars %>% 
  ggplot(aes(mpg)) +
  geom_density(aes(fill = factor(cyl)),alpha = 0.5) +
  scale_x_continuous(expand = c(0,0)) +
  scale_y_continuous(expand = c(0,0)) +
  scale_fill_brewer(palette = "Set2") +
  scale_fill_discrete(name = "Cyl") +
  theme(axis.title = element_text(size = 12),
        axis.text = element_text(size = 10))
## Scale for 'fill' is already present. Adding another scale for 'fill', which
## will replace the existing scale.

1.5.13 方块图绘制相关系数图

corr <- round(cor(mtcars), 2)
df <- reshape2::melt(corr)

df %>% head()
##   Var1 Var2 value
## 1  mpg  mpg  1.00
## 2  cyl  mpg -0.85
## 3 disp  mpg -0.85
## 4   hp  mpg -0.78
## 5 drat  mpg  0.68
## 6   wt  mpg -0.87
ggplot(df, aes(x=Var1, y=Var2, fill=value, label=value)) + 
  geom_tile() + 
  theme_bw() + 
  geom_text(aes(label=value, size=value), color="white") + 
  labs(title="mtcars - Correlation plot") + 
  theme(text=element_text(size=20), 
        plot.title = element_text(hjust = 0.5),
        legend.position="none") +
  scale_x_discrete(expand = c(0,0)) +
  scale_y_discrete(expand = c(0,0))->gg

library(RColorBrewer)
p2 <- gg + scale_fill_distiller(palette="Reds")
p3 <- gg + scale_fill_gradient2()
gridExtra::grid.arrange(gg, p2, p3, nrow=3)