- 绘制点图的data有四列xvalue、yvalue、class1、class2
- 这里要对四种类型的点的数量用柱形图统计,叠加在点图上
结果图
x1 <- get_pos(data$xvalue, 0.05) # 柱子的位置,设置为数据的5%位置
x2 <- get_pos(data$xvalue, 0.95)
ym <- get_pos(data$yvalue, 0.05)
width <- (max(data$xvalue) - min(data$xvalue)) * 0.05 # 柱子的宽度,根据数据的范围来定
yscale <- (max(data$yvalue) - min(data$yvalue)) * 0.001 # 柱子高度的缩放值,根据数据的范围来定
# 柱子位置以及高度
data.bar <- data.frame(
x = c(
x1-width/2,
x1+width/2,
x2-width/2,
x2+width/2),
y = c(
nrow(data[data$class1 == 'shorter' & data$class2 == 'down',]),
nrow(data[data$class1 == 'shorter' & data$class2 == 'up',]),
nrow(data[data$class1 == 'longer' & data$class2 == 'down',]),
nrow(data[data$class1 == 'longer' & data$class2 == 'up',])
),
class2 = c('down', 'up', 'down', 'up')
)
xlab <- 'xlab'
ylab <- 'ylab'
title <- 'title'
file <- 'file.pdf'
fig <- ggplot(data = data, aes(x = xvalue, y = yvalue)) +
scale_color_manual(values = c("blue", "grey", "red")) + # 设置color颜色
geom_point(aes(color = class2), alpha = 0.6, size = 1.5) +
guides(color = "none") + # 不显示geom_point的color的图例
# geom_rect实际是绘制一个矩形,aes中的x,y是矩形的中心点,xmin,xmax,ymin,ymax是矩形的四个顶点, 单独绘制geom_rect时不需要指定x和y, 如果不指定在这里会报错,实际不起作用
geom_rect(data = data.bar, aes(x=0,y=0,xmin = x - width/2, xmax = x + width/2, ymin = ym, ymax = y * yscale + ym, fill = class2)) +
scale_fill_manual(values = c("blue", "red")) + # 设置fill颜色
geom_text(data= data.bar,aes(x = x, y= y * yscale - 2,label=y),vjust=-0.5) +
theme_bw(base_size = 12) +
geom_vline(xintercept = 0, lty = 1, col = "black", lwd = 0.3) +
theme(
# legend.position="none",
panel.grid = element_blank(),
plot.title = element_text(hjust = 0.5),
legend.text = element_text(color = "black", size = 8),
axis.text = element_text(color = "black", size = 12),
axis.title = element_text(color = "black", size = 12)
) +
labs(x = xlab, y = ylab, title = title)
ggsave(file, width = 10, height = 8, limitsize = FALSE)
get_pos <- function(x, prob) {
x <- as.vector(na.omit(x))
range <- max(x) - min(x)
return(min(x) + prob * range)
}