做这幅图不是为了说明R做的图有多酷炫(虽然R做的图确实很优雅),而是极尽一切可能去挖掘ggplot2包的潜能,对一幅统计图的各个要素进行随心所欲的定制,达到客户多样性需求。talk is cheep,show you the code!

 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
library(tidyverse)
library(gcookbook)

heightweight %>%
  mutate(sex=factor(sex,levels = c("m","f"),
                    labels = c("Male","Famale"))) %>%
  ggplot(aes(ageYear,heightIn,color=sex, shape=sex))+
  geom_point()+
  geom_smooth(method = "lm")+
  scale_color_manual(values = c("darkred", "darkblue"),
                     labels = c("Male", "Famale"))+
  scale_shape_manual(values = c(21,24),
                     labels = c("Male", "Famale"))->p

p +
  ggtitle("Plot title here")+
  theme(
    # 绘图区域选项
    panel.grid.major = element_line(color="wheat3"),
    panel.grid.minor = element_line(color="red",linetype = "dashed",size=0.2),
    panel.background = element_rect(fill="honeydew"),
    panel.border = element_rect(color = "blue",size=1,fill=NA))+
  
  # 坐标轴及标题文本项目选项
  theme(
    axis.title.x=element_text(color="mediumpurple",size=14,face = "bold"),
    axis.title.y=element_text(color="#FFDDAA",size=14,angle=90,face = "bold.italic"),
    axis.text.x=element_text(color="khaki4",size=12),
    axis.text.y=element_text(color="blue"),
    axis.line = element_line(size = 4,color="black",lineend = "square"),
    plot.title=element_text(color="darkred", face = "bold",
                            size=20, hjust = 0, angle=180))+
  
  # 图例选项
  theme(
    legend.position = c(0,1),
    legend.justification = c(0,1),
    legend.background = element_rect(fill="grey85",color="magenta3",size=1),
    legend.title = element_text(color = "blue",face="bold",size=14),
    legend.text = element_text(color="yellow"),
    legend.key = element_rect(color="green",size=0.25)) +
  
  
  # 修改刻度标签的文本
  scale_y_continuous(breaks = c(50,56,60,66,72),
                     labels = c("Tiny",
                                "Really\nshort",
                                "Short","Medium",
                                "Tallish"))+
  
  # 添加矩形阴影区域
  annotate("rect",
           xmin = 13.5, xmax = 14.5,
           ymin = 50, ymax = 72,
           alpha=0.1,fill="red")+
  
  # 添加带有箭头的线段
  annotate("segment",x=13,xend=15,y=50,yend=55,
           size=2,color="green",
           arrow=arrow(angle = 60))+
  
  # 添加地毯
  geom_rug(sides = "b")+
  
  # 分面选项
  facet_grid(sex ~ .)+
  theme(
    strip.background = element_rect(fill="lightblue",color="turquoise4",size=0.8),
    strip.text.y = element_text(size=14,angle = 90,face="bold",color="white"))