简体   繁体   English

不同的y轴标签facet_grid和尺寸

[英]Different y-Axis Labels facet_grid and sizes

I'am stuck with the following problem: 我遇到了以下问题:

I want to display different characteristics of a timeseries in one plot (with multiple subplots). 我想在一个图中显示时间序列的不同特征(具有多个子图)。 To align the chart areas and for easy creation I use ggplot2 and its facet_grid function. 为了对齐图表区域并便于创建,我使用ggplot2及其facet_grid函数。

However, I want to change just one axis label (eg. the upper plot to percent). 但是,我想只更改一个轴标签(例如,上图为百分比)。

Furthermore, I want to resize the heights of each plot, so that the upper plot is roughly twice as large as the lower one. 此外,我想调整每个绘图的高度,以便上面的图大约是下图的两倍大。

Thank you very much for your help! 非常感谢您的帮助!

Example

require(ggplot2)

#simulate some data
df <- data.frame(date=c(1:1000),
              value=cumsum(rnorm(1000)),
              volume=abs(rnorm(1000)*10))

#melt for ggplot
df_melt <- melt(df, id=c("date"),measure.vars=c("value","volume"))

#plot
ggplot(df_melt, aes(x=date, y=value)) + geom_line() + 
       facet_grid(variable~., scales = "free")

which results in something like this: 结果是这样的: 在此输入图像描述

You can change the grobs of your plot to do this 您可以更改绘图的grobs来执行此操作

library(ggplot2)
library(grid)
library(scales)

#plot
p <- ggplot(df_melt, aes(x=date, y=value)) + 
            geom_line() + 
            facet_grid(variable~., scales = "free")

# change facet heights
g1 <- ggplotGrob(p) 
g1$heights[[3]] <- unit(2, "null") 

# change labels - create second plot with percentage labels (nonsese % here)
p2 <- ggplot(df_melt, aes(x=date, y=value)) + 
              geom_line() + 
              facet_grid(variable~., scales = "free") +
              scale_y_continuous(labels = percent_format())

g2 <- ggplotGrob(p2) 

#Tweak axis - overwrite one facet
g1[["grobs"]][[2]] <- g2[["grobs"]][[2]]

grid.newpage()
grid.draw(g1)

在此输入图像描述

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

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