r - 在 R 中的序列中优雅地为 ggplot2 轴标签创建字符串

标签 r ggplot2

我正在尝试用年份标记 ggplot,但保持 3 个月的刻度线,因此需要:

labels = c(0,"","","", 12,"","","", 24,"","","", 36...)

稍微整洁的是:

labels = c(0,rep("",3),12,rep("",3),24,rep("",3),36...)

必须可以通过编程方式创建它。

gsub("," , ",'','',''," ,"0,12,24,36" )

很接近,但我管理过的唯一实际工作解决方案是

labels=c()
for (i in 0:3){ labels<-c(labels,i*12,rep("",3)) }

我确信一定有一个优雅的解决方案,有人能想出一个吗?

最佳答案

我会使用 seq 创建一个向量,并使用模运算符 (%%) 来删除我不想要的条目...

# Some data
df <- data.frame( x=seq(0,36) , y = rnorm(37) )

# Make quarterly labels  
lab <- seq(0,36,by=3)

# Blank everything that is not evenly divisible by 12 months
lab[ lab %% 12 > 0 ] <- ""

# Plot
ggplot( df , aes(x,y) ) + geom_point() +
  scale_x_continuous( breaks = seq(0,36,by=3) , labels = lab )

enter image description here

关于r - 在 R 中的序列中优雅地为 ggplot2 轴标签创建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23290056/

相关文章:

r - 如何组合多个 .csv 文件,并在 R 中添加一个包含每个数据集名称的列?

r - 循环为数据框中的变量生成绘图

r 结合 ggRadar 和 facet_wrap

r - geom_boxplot() : forcing an empty level to appear

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

r - 计算 2 个经纬度之间的距离

r - ffbase::as.character 中的 "by"参数有什么作用?

javascript - 将 onRender() 函数中创建的对象保存在 htmlWidgets 中

r - 根据条件和 groupby 更新列

r - ggplot2 - 在哪里 build 秤?