ggplot2:没有标签的刻度标记有较短的刻度线

bai*_*ong 11 r ggplot2

我有一个使用ggplot2的情节,其中我想沿着x轴有许多刻度线,但只有一些刻度线会有与它们相关的刻度标签.但是,我希望那些标签的标记长于不标记的标记.

jba*_*ums 9

在基数R中,您可以使用初始plot调用(with xaxt='n')来抑制x轴,然后使用两个调用tcl来控制标记长度(请参阅?par)axis(1, ...).

plot(1:10, xaxt='n', ylab='', las=1)
axis(1, at=1:10, tcl=-0.8)
axis(1, at=seq(0, 11, 0.2), labels=NA)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • @smci无所谓,仍然很棒. (3认同)
  • 不错,但 OP 要求使用 ggplot,而不是基础 R 图形 (2认同)

San*_*att 5

使用基本图形更容易,但这是使用ggplot2的尝试。

该方法基于此方法该方法将空白标签插入标签序列(使用该答案中的代码)。一旦中断和标签在ggplot中就位,我就会钻研该图的结构以编辑刻度线的长度。(小心使用;不难打破。)

library(ggplot2)
library(grid)

# Data
 df = data.frame(x = 1:10, y = 1:10)

# Range of x values
range = 1:10

# Major tick marks
major = 1

# Minor tick marks
minor = 0.2

# Function to insert blank labels
# Borrowed from /sf/ask/1014305001/#14490652
insert_minor <- function(major, n_minor) {
      labs <- c(sapply(major, function(x, y) c(x, rep("", y) ), y = round(n_minor)))
      labs[1:(length(labs) - n_minor)]
}

# Getting the 'breaks' and 'labels' for the ggplot
n_minor = major/minor - 1
breaks = seq(min(range), max(range), minor)
labels = insert_minor(seq(min(range), max(range), major), n_minor)
if(length(breaks) > length(labels)) labels = c(labels, rep("", length(breaks) - length(labels)))

# The plot
p <- ggplot(df, aes(x = x, y = y)) + 
     geom_point() + 
     scale_x_continuous(breaks = breaks, labels = labels) + 
     coord_cartesian(xlim = range) +
     theme_bw() +
     theme(panel.grid = element_blank(),
           axis.text.x = element_text(margin = margin(t = 5, unit = "pt")))
p

# Edit the plot:
# Change the lengths of the major tick marks

g = ggplotGrob(p)

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

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

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

# Edit the y positions of the end points of the tick marks
# The '6' and the '3' in the code below 
# are the lengths in pts of the major and minor tick marks respectively. 
marks$y = unit.c(unit.c(unit(1, "npc") - unit(6, "pt"), unit(1, "npc"),   
                 rep(unit.c(unit(1, "npc") - unit(3, "pt"), unit(1, "npc")), n_minor)))

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

# Draw the plot
grid.newpage()
grid.draw(g)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • *注意:*我们已针对Facett网格图调整了此解决方案,请参阅:/sf/ask/3756249241/ (2认同)

And*_*lor 0

theme(axis.ticks.length)

http://docs.ggplot2.org/0.9.2.1/theme.html应该很有用。

编辑抱歉,请仔细阅读您的问题。标记的是标准的 Major.grid 刻度吗?或以某种自定义方式标记?