我有以下两个问题: (1) 我想让标签位于两个刻度之间。我最初的想法是添加辅助刻度并删除主要刻度,但是 axis.minor.ticks.length.y 不起作用 (2)在图例处添加stat_summary点 非常感谢您回答您的问题!
这是代码和图:
library("ggplot2")
dt <- data.frame(
ca = rep(c("Oesophageal cancer", "Gastric cancer", "Colorectal cancer"), 3),
var1 = c(1:3, -4:-6, 7:9),
var2 = rep(LETTERS[1:3], 3)
)
dt %>%
ggplot(aes(var1, ca, fill = var2))+
geom_bar(stat="identity", width=0.8)+
stat_summary(fun=sum, geom="point",colour="grey40", fill="grey40", shape=20, size=2)+
geom_vline(xintercept=0, colour="grey30", linetype="dotted")+
theme(
axis.minor.ticks.length.y = rel(0.5)
)
目标:将图1改为图2风格
据我所知,ggplot2 没有在轴中断之间添加辅助刻度的功能。但由于 ggplot2 的灵活性,我们可以手动添加它们,无需太多麻烦,只需在垂直轴上绘制一些线(线段),并添加一个设置,以便绘图边界之外的图形元素不会被删除。
library(ggplot2)
library(dplyr)
dt <- data.frame(
ca = rep(c("Oesophageal cancer", "Gastric cancer", "Colorectal cancer"), 3),
var1 = c(1:3, -4:-6, 7:9),
var2 = rep(LETTERS[1:3], 3)
)
#values for the y axis that will place the ticks just between every text label
middle_ticks_positions <- seq(0.5, length(unique(dt$ca))+0.5, by = 1)
#hard limits for the x axis that will allow us to draw elements in the plot without stretching the vertical axis to fit them
limits_x_axis <- c(min(dt$var1)*1.2, max(dt$var1)*1.5)
dt %>%
ggplot(aes(var1, ca, fill = var2))+
geom_bar(stat="identity", width=0.8)+
annotate("segment",
x = -8.2, xend = -8.6, #adjust the length of ticks as you need
y = middle_ticks_positions, yend = middle_ticks_positions) +
coord_cartesian(clip = "off", xlim = limits_x_axis) +
stat_summary(fun=sum, geom="point",colour="grey40", fill="grey40", shape=20, size=2)+
geom_vline(xintercept=0, colour="grey30", linetype="dotted")+
theme(
axis.ticks.y = element_blank()
)