使用带有facet_wrap的ggplot2显示不同的轴标签 [英] Showing different axis labels using ggplot2 with facet_wrap

查看:326
本文介绍了使用带有facet_wrap的ggplot2显示不同的轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间序列,具有不同的变量和不同的单位,我希望在同一图上显示它们.

I have a time series with different variables and different units that I want to display on the same plot.

ggplot不支持多轴(

ggplot does not support multiple axis (as explained here), so I followed the advice and tried to plot the curves with facets:

x <- seq(0, 10, by = 0.1)
y1 <- sin(x)
y2 <- sin(x + pi/4)
y3 <- cos(x)

my.df <- data.frame(time = x, currentA = y1, currentB = y2, voltage = y3)
my.df <- melt(my.df, id.vars = "time")
my.df$Unit <- as.factor(rep(c("A", "A", "V"), each = length(x)))

ggplot(my.df, aes(x = time, y = value)) + geom_line(aes(color = variable)) + facet_wrap(~Unit, scales = "free_y", nrow = 2)

结果如下:

问题是,只有一个y标签,上面写着值",我想两个:一个带有"Currents(A)",另一个带有"Voltage(V)".

The thing is that there is only one y label, saying "value" and I would like two: one with "Currents (A)" and the other one with "Voltage (V)".

这可能吗?

推荐答案

ggplot2_2.2.1.中,您可以使用strip.position参数将面板条移动为y轴标签. >.但是,使用这种方法,您将不会同时拥有条形标签和不同的y轴标签.

In ggplot2_2.2.1 you could move the panel strips to be the y axis labels by using the strip.position argument in facet_wrap. Using this method you don't have both strip labels and different y axis labels, though, which may not be ideal.

将条形标签放置在y轴(左侧")上后,可以通过给labeller提供一个命名矢量来用作查找表来更改标签.

Once you've put the strip labels to be on the y axis (the "left"), you can change the labels by giving a named vector to labeller to be used as a look-up table.

可以通过theme中的strip.placement将带状标签移动到y轴之外.

The strip labels can be moved outside the y-axis via strip.placement in theme.

删除条形背景和y轴标签,以得到带有两个窗格和不同的y轴标签的最终图形.

Remove the strip background and y-axis labels to get a final graphic with two panes and distinct y-axis labels.

ggplot(my.df, aes(x = time, y = value) ) + 
     geom_line( aes(color = variable) ) + 
     facet_wrap(~Unit, scales = "free_y", nrow = 2, 
                strip.position = "left", 
                labeller = as_labeller(c(A = "Currents (A)", V = "Voltage (V)") ) )  +
     ylab(NULL) +
     theme(strip.background = element_blank(),
           strip.placement = "outside")

从顶部移除条带会使两个窗格靠得很近.要更改间距,您可以将panel.margin = unit(1, "lines")添加到theme.

Removing the strip from the top makes the two panes pretty close together. To change the spacing you can add, e.g., panel.margin = unit(1, "lines") to theme.

这篇关于使用带有facet_wrap的ggplot2显示不同的轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆