R ggplot2:y轴标签在打印区域内左对齐
我正在寻找一种自动移动y轴刻度标签的方法,以便它们在实际绘图区域内左对齐。我喜欢ggplot中主题组件的一般灵活性,但在试图找到一种通用方法时遇到了麻烦 我知道给定轴.text.y一个组合的R ggplot2:y轴标签在打印区域内左对齐,r,ggplot2,R,Ggplot2,我正在寻找一种自动移动y轴刻度标签的方法,以便它们在实际绘图区域内左对齐。我喜欢ggplot中主题组件的一般灵活性,但在试图找到一种通用方法时遇到了麻烦 我知道给定轴.text.y一个组合的hjust=0和一个负的右边距(*gag*)可以达到这个效果,但是负边距必须手动设置以匹配最长的y轴刻度标签的宽度 作为一个例子,考虑下面的代码: library(ggplot2) set.seed(0) dat <- data.frame(x = 1:100, y = (1:100) + runif
hjust=0
和一个负的右边距(*gag*)可以达到这个效果,但是负边距必须手动设置以匹配最长的y轴刻度标签的宽度
作为一个例子,考虑下面的代码:
library(ggplot2)
set.seed(0)
dat <- data.frame(x = 1:100, y = (1:100) + runif(100, -10, 10))
p1 <- ggplot(dat, aes(x, y)) +
geom_line() +
scale_y_continuous("", breaks = c(0, 30, 60, 90),
labels = c(0, 30, 60, "90 units of something")) +
theme(axis.text.y = element_text(hjust = 0,
margin = margin(0, -3.1, 0, 0, 'cm')))
库(ggplot2)
种子集(0)
dat这里有一个使用grobs的方法,它将y轴标签从其原始位置移开,以重叠绘图区域
虽然我认为它不是很优雅(它是一个黑客程序,它需要在<代码> GGPROTROGRB 中进行转换),但是定位并不是硬编码的,你可以在转换之前指定<代码> GGPROTH()/<代码>中想要的任何主题控件。
设置:
library(ggplot2)
library(grid)
library(gtable)
# sample data
set.seed(0)
dat <- data.frame(x=1:100, y=(1:100) + runif(100, -10, 10))
# create ggplot object
p <- ggplot(dat, aes(x, y)) +
geom_line() +
scale_y_continuous("",
breaks = c(0, 30, 60, 90),
labels = c(0, 30, 60, "90 units of something")) +
# left-align y-axis labels
# you can also specify other theme parameters as desired
theme(axis.text.y = element_text(hjust = 0))
粗糙的方法,但<代码>ggplot(dat,aes(x,y))+geom_line()+比例y连续(“,breaks=c(0,30,60,90))+注释(“text”,x=-Inf,y=c(0,30,60,90),label=c(0,30,60,90个单位),hjust=0)+主题(axis.text.y=element_blank())
谢谢!我曾经玩过类似的东西,但我讨厌你失去对记号标签的主题控制。同意,也许有一种方法可以使用来自或,但有点深奥的想法,你说的“失去对记号标签的主题控制”是什么意思?
# convert from ggplot to grob object
gp <- ggplotGrob(p)
# locate the grob that corresponds to y-axis labels
y.label.grob <- gp$grobs[[which(gp$layout$name == "axis-l")]]$children$axis
# remove y-axis labels from the plot, & shrink the space occupied by them
gp$grobs[[which(gp$layout$name == "axis-l")]] <- zeroGrob()
gp$widths[gp$layout$l[which(gp$layout$name == "axis-l")]] <- unit(0, "cm")
# create new gtable
new.y.label.grob <- gtable(heights = unit(1, "npc"))
# place axis ticks in the first column
new.y.label.grob <- gtable_add_cols(new.y.label.grob,
widths = y.label.grob[["widths"]][2])
new.y.label.grob <- gtable_add_grob(new.y.label.grob,
y.label.grob[["grobs"]][[2]],
t = 1, l = 1)
# place axis labels in the second column
new.y.label.grob <- gtable_add_cols(new.y.label.grob,
widths = y.label.grob[["widths"]][1])
new.y.label.grob <- gtable_add_grob(new.y.label.grob,
y.label.grob[["grobs"]][[1]],
t = 1, l = 2)
# add third column that takes up all the remaining space
new.y.label.grob <- gtable_add_cols(new.y.label.grob,
widths = unit(1, "null"))
gp <- gtable_add_grob(gp,
new.y.label.grob,
t = gp$layout$t[which(gp$layout$name == "panel")],
l = gp$layout$l[which(gp$layout$name == "panel")])
grid.draw(gp)