下面是一个情节的示例代码,它几乎完全符合我的要求。我唯一想添加的是根据下面定义的 minor_breaks 在 x 轴上的刻度线(与主要刻度相同的大小)。
df <- data.frame(x = c(1900,1950,2000), y = c(50,75,60))
p <- ggplot(df, aes(x=x, y=y))
p + geom_line() +
scale_x_continuous(minor_breaks = seq(1900,2000,by=10), breaks = seq(1900,2000,by=50), limits = c(1900,2000), expand = c(0,0)) +
scale_y_continuous(breaks = c(20,40,60,80), limits = c(0,100)) +
theme(legend.position="none", panel.background = element_blank(),
axis.line = element_line(color='black'), panel.grid.minor = element_blank())
提前致谢,
--JT
最佳答案
这将在精确的情况下做到这一点:
scale_x_continuous(breaks= seq(1900,2000,by=10),
labels = c(1900, rep("",4), 1950, rep("",4), 2000),
limits = c(1900,2000), expand = c(0,0)) +
这是一个不是防弹的函数,但可以在开始和结束主要标签与
at
的开始和停止值对齐时插入空白标签。争论:insert_minor <- function(major_labs, n_minor) {labs <-
c( sapply( major_labs, function(x) c(x, rep("", 4) ) ) )
labs[1:(length(labs)-n_minor)]}
测试:
p <- ggplot(df, aes(x=x, y=y))
p + geom_line() +
scale_x_continuous(breaks= seq(1900,2000,by=10),
labels = insert_minor( seq(1900, 2000, by=50), 4 ),
limits = c(1900,2000), expand = c(0,0)) +
scale_y_continuous(breaks = c(20,40,60,80), limits = c(0,100)) +
theme(legend.position="none", panel.background = element_blank(),
axis.line = element_line(color='black'), panel.grid.minor = element_blank())
关于r - 向 ggplot2 中的 x 轴添加小刻度线(无标签),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14490071/