首页 > 解决方案 > 在 ggplot2 中自定义轴刻度

问题描述

我有以下数据

df <- data.frame(dose=c("D0.5", "D1", "D2"),
                 len=c(4.2, 10, 29.5))

library(ggplot2)
# Basic barplot
p<-ggplot(data=df, aes(x=dose, y=len)) +
  geom_bar(stat="identity") + 
  theme(axis.ticks.y = element_blank())
p
# Horizontal bar plot
p + coord_flip()

这给了我以下图表 在此处输入图像描述

我想使用黑色刻度在下面显示的位置添加刻度

在此处输入图像描述

请有人建议我如何在ggplot2中实现这一点。

标签: rggplot2axis-labels

解决方案


您可以尝试类似于此答案

library(grid)
# the plot
g <- ggplot(data=df, aes(x=as.numeric(dose), y=len)) +
      geom_col() + coord_flip() +
        scale_x_continuous(breaks = seq(0.5, 3.5,0.5), 
                           labels = c("", "D0.5", "", "D1", "", "D2","")) +
      xlab("")

# Change the lengths of the tick marks
g = ggplotGrob(g)

# Get the x axis on the left side
xaxis <- g$grobs[[which(g$layout$name == "axis-l")]]  

# Get the tick marks and tick mark labels   
ticks <- xaxis$children[[2]]

# Get the tick marks
marks = ticks$grobs[[2]]

# change the length in an alternating way

long <- unit.c(unit(1, "npc") - unit(40, "pt"), unit(1, "npc"))
short <- unit.c(unit(1, "npc") - unit(3, "pt"), unit(1, "npc"))

# update the length
marks$x = unit.c(rep(unit.c(long, short), 3), long)

# Put the tick marks back into the plot
ticks$grobs[[2]] = marks
xaxis$children[[2]] = ticks
g$grobs[[which(g$layout$name == "axis-l")]]  = xaxis

# Draw the plot
grid.draw(g)

在此处输入图像描述


推荐阅读