简体   繁体   English

如何在R中的ggplot2中设置y轴刻度标签的宽度?

[英]How to set width of y-axis tick labels in ggplot2 in R?

I would like to left align the plot panels in a vertical array of ggplot2 graphs in R. The maximum width of the y-axis tick labels varies from graph to graph, breaking this alignment, as shown in the sample code below. 我想在R中的ggplot2图形的垂直数组中使绘图面板左对齐。y轴刻度标签的最大宽度因图形而异,破坏了这种对齐方式,如下面的示例代码所示。

I've tried various plot, panel, and axis.text margin options without success, and have not been able to find an option for controlling the width of the y-axis tick labels. 我尝试了各种图,面板和axis.text页边距选项,但均未成功,并且无法找到控制y轴刻度标签宽度的选项。

Guidance appreciated. 指导表示赞赏。

#install.packages(c("ggplot2", "gridExtra", "reshape2"), dependencies = TRUE)
require(ggplot2)
require(gridExtra)
require(reshape2)

v <- 1:5
data1 <- data.frame(x=v, y=v)
data2 <- data.frame(x=v, y=1000*v)
plot1 <- ggplot(data=melt(data1, id='x'), mapping=aes_string(x='x', y='value')) + geom_line()
plot2 <- ggplot(data=melt(data2, id='x'), mapping=aes_string(x='x', y='value')) + geom_line()
grid.arrange(plot1, plot2, ncol=1) 

You can use function plot_grid() from library cowplot to align plots 您可以使用库cowplot函数plot_grid()来对齐图

# install.packages(c("ggplot2", "cowplot", "reshape2"), dependencies = TRUE)
library(cowplot)
plot_grid(plot1,plot2,ncol=1,align="v")

在此处输入图片说明

would this something like that work for you: 这样的事情对您有用吗?

data1$Data <- "data1"
data2$Data <- "data2"
data3 <- rbind(data1, data2)
ggplot(data=data3, aes(x=x, y=y)) + geom_line() + facet_grid(Data~., scales = "free_y")

在此处输入图片说明

like this? 像这样? (code below) (下面的代码)

在此处输入图片说明

# install.packages(c("ggplot2", "gridExtra", "reshape2"), dependencies = TRUE)
require(ggplot2)
require(gridExtra)
require(reshape2)

v <- 1:5
data1 <- data.frame(x=v, y=v)
data2 <- data.frame(x=v, y=1000*v)
plot1 <- ggplot(data=melt(data1, id='x'), mapping=aes_string(x='x', y='value')) + geom_line() + scale_y_continuous(breaks=NULL)
plot2 <- ggplot(data=melt(data2, id='x'), mapping=aes_string(x='x', y='value')) + geom_line() + scale_y_continuous(breaks=c(1000,2000))
grid.arrange(plot1, plot2, ncol=1) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM