0%

ggplot2集锦之六绘制各种图形4

本文总结一下基于ggplot2包绘制各种类型的图,本文包括:棒棒糖图、哑铃图。

1. 棒棒糖图

棒棒糖图本质是点图加上柱状图/线段。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
data <- diamond[c(1:10),]
data$name <- c("A","B","C","D","E","F","G","H","I","J")
data
# A tibble: 10 x 11
carat cut color clarity depth table price x y z name
<dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl> <chr>
1 0.61 Good E I1 63.4 57.1 1168 5.37 5.43 3.42 A
2 0.53 Premium G SI2 60.8 58 1173 5.21 5.19 3.16 B
3 0.23 Very Good E VVS2 62.3 55 505 3.9 3.93 2.44 C
4 1.33 Ideal J VS1 61.3 57 6118 7.11 7.08 4.35 D
5 0.3 Ideal E VVS1 61.6 56 838 4.3 4.34 2.66 E
6 0.3 Ideal D VS2 60.8 57 911 4.34 4.31 2.63 F
7 2.01 Good H I1 63.9 59 7024 8.01 7.92 5.09 G
8 1.12 Ideal H VS2 61.8 55 6110 6.64 6.7 4.12 H
9 1.02 Ideal G VVS2 62.1 57 8401 6.43 6.45 4 I
10 0.74 Ideal F VS1 62.3 56 3226 5.76 5.79 3.6 J

绘制散点加线段。

1
2
3
ggplot(data,aes(x = reorder(name,price),y = price))+
geom_point()+
geom_segment(aes(x = name,xend=name,y=0,yend=price))

修改y轴基线更改设定的阈值。

1
2
3
ggplot(data,aes(x = reorder(name,price),y = price))+
geom_point()+
geom_segment(aes(x = name,xend=name,y=2000,yend=price))

美化:

1
2
3
4
ggplot(data,aes(x = reorder(name,price),y = price))+
geom_segment(aes(x = reorder(name,price),xend=name,y=2000,yend=price),
linewidth=1.5,color="#C9CACA",linetype="solid")+
geom_point(size=5,color="#74C6BE",fill="#74C6BE",shape=21)

翻转,横向棒棒糖图:

1
2
3
4
5
ggplot(data,aes(x = reorder(name,price),y = price))+
geom_segment(aes(x = reorder(name,price),xend=name,y=2000,yend=price),
linewidth=1.5,color="#C9CACA",linetype="solid")+
geom_point(size=5,color="#74C6BE",fill="#74C6BE",shape=21)+
coord_flip()

alt 图标

ifelse修改指定感兴趣的点的样式:

1
2
3
4
5
6
7
8
ggplot(data,aes(x = reorder(name,price),y = price))+
geom_segment(aes(x = reorder(name,price),xend=name,y=0,yend=price),
size=ifelse(data$name%in%c("A","I"),3,1.5),
color=ifelse(data$name%in%c("A","I"),"#f6b37f","#C9CACA"))+
geom_point(size=ifelse(data$name%in%c("A","I"),8,5),
color=ifelse(data$name%in%c("A","I"),"#f6b37f","#74C6BE"),
fill=ifelse(data$name%in%c("A","I"),"#f6b37f","#74C6BE"))+
coord_flip()

alt 图标

如果想要不同的颜色,那么加一个分组变量即可。

2. 哑铃图

哑铃图本质是不同分组的点图加两个点之间的线段。

1
2
3
4
data
name group1 group2
A 100 200
B 129 389

构造数据:

1
2
3
4
5
6
7
data$price2 <- data$price/2

ggplot(data) +
geom_segment(aes(x=reorder(name,price), xend=reorder(name,price),y=price,yend=price2),color="grey",linewidth=1.5) +
geom_point(aes(x=reorder(name,price), y=price),color="#A4B8F7",size=5) +
geom_point(aes(x=reorder(name,price), y=price2),color="#F484B2",size=5)+
coord_flip()

alt 图标

参考资料:

  1. https://zhuanlan.zhihu.com/p/448849834