r - 向 ggplot2 中的 x 轴添加小刻度线(无标签)

标签 r ggplot2

下面是一个情节的示例代码,它几乎完全符合我的要求。我唯一想添加的是根据下面定义的 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/

相关文章:

r - 在 ggplot2 中正确使用 fun.data 和 stat_summary?

r - R中同一时间序列图有多种颜色,可能吗?

css - DT Shiny 不同的自定义列标题按列

r - 如何从多元回归模型中提取置信区间?

r - 如何创建要插入到 ggplot 中的对象(当有多个带 + 的部分时)?

r - 在点周围放置边框

r - 带有代表绝对大小的气泡的气泡图

r - 如何在多面板图的面板上绘制箭头?

r - 在 Shiny 的应用程序中插入已编辑的数据表值

R -- 编辑 'nnet' 包