R语言-绘制不等宽柱形图

R语言-绘制不等宽柱形图

这个图是寒假的时候学习杜雨的推文的笔记,回头再看觉得画的也不怎么样,进行了一些修改:

R
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
library(ggplot2)
library(scales)
mydata <- data.frame(Name = paste0("Pjt", 1:5), Scale = c(35, 30, 20, 10, 5), ARPU = c(56, 37, 63, 57, 59))
# 在ggplot2的系统里面,生成矩阵的图层函数是geom_rect()函数,内置四个参数:xmin/xmax/ymin/ymax
# 构造x轴的起点
mydata$xmin <- 0
for (i in 2:5){
mydata$xmin[i] <- sum(mydata$Scale[1:i-1])
}
# 构造矩形的终点
for (i in 1:5){
mydata$xmax[i] <- sum(mydata$Scale[1:i])
}

# 构造数据标签的横坐标:
for (i in 1:5){
mydata$label[i] <- sum(mydata$Scale[1:i])-mydata$Scale[i]/2
}

ggplot(mydata) +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = 0, ymax = ARPU, fill = Name)) +
scale_fill_manual(values = c("#54576B", "#BD1F12", "#E8BA11", "#62962A", "#9B56AF")) +
geom_text(aes(x = label, y = ARPU - 3, label = ARPU), size = 6, col = "white") +
geom_text(aes(x = label, y = 3, label = Scale), size = 6, col = "white") +
geom_text(aes(x = label, y = -3, label = Name), size = 6, col = "black") +
labs(title = "图:不等宽柱形图",
subtitle = "数据来源:EasyChart") +
ylim(-10, 80) +
theme_void(base_family = "STSong", base_size = 20) +
theme(legend.position = "none") +
theme(plot.title = element_text(hjust = 0.5)) +
theme(plot.subtitle = element_text(hjust = 0.5))

# R

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×