在ggplot2中自定义轴刻度

时间:2018-05-24 12:16:11

标签: r ggplot2 axis-labels

我有以下数据

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()

给出了以下图表 enter image description here

我想使用黑色刻度

在下面显示的位置添加刻度线

enter image description here

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

1 个答案:

答案 0 :(得分:0)

您可以尝试类似于此answer

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)

enter image description here