19

我正在创建一个图表,显示湖水位随时间的变化。我在下面附上了一个简单的例子。我想在绘图的右侧添加一个刻度(刻度线和注释),以英尺为单位显示高程。我知道 ggplot2 不允许使用两种不同的比例(请参阅Plot with 2 y 轴,一个 y 轴在左侧,另一个 y 轴在右侧),但是因为这是相同比例的转换,有没有办法做这个?我宁愿继续使用 ggplot2 而不必恢复到 plot() 函数。

library(ggplot2)
LakeLevels<-data.frame(Day=c(1:365),Elevation=sin(seq(0,2*pi,2*pi/364))*10+100)
p <- ggplot(data=LakeLevels) + geom_line(aes(x=Day,y=Elevation)) + 
  scale_y_continuous(name="Elevation (m)",limits=c(75,125)) 
p
4

4 回答 4

16

你应该看看这个链接http://rpubs.com/kohske/dual_axis_in_ggplot2

我已经为您的示例调整了那里提供的代码。这个修复看起来很“hacky”,但它让你成为了其中的一部分。剩下的唯一部分是弄清楚如何将文本添加到图形的右轴。

    library(ggplot2)
    library(gtable)
    library(grid)
    LakeLevels<-data.frame(Day=c(1:365),Elevation=sin(seq(0,2*pi,2*pi/364))*10+100)
    p1 <- ggplot(data=LakeLevels) + geom_line(aes(x=Day,y=Elevation)) + 
          scale_y_continuous(name="Elevation (m)",limits=c(75,125))

    p2<-ggplot(data=LakeLevels)+geom_line(aes(x=Day, y=Elevation))+
        scale_y_continuous(name="Elevation (ft)", limits=c(75,125),           
        breaks=c(80,90,100,110,120),
                 labels=c("262", "295", "328", "361", "394"))

    #extract gtable
    g1<-ggplot_gtable(ggplot_build(p1))
    g2<-ggplot_gtable(ggplot_build(p2))

    #overlap the panel of the 2nd plot on that of the 1st plot

    pp<-c(subset(g1$layout, name=="panel", se=t:r))
    g<-gtable_add_grob(g1, g2$grobs[[which(g2$layout$name=="panel")]], pp$t, pp$l, pp$b, 
                       pp$l)

   ia <- which(g2$layout$name == "axis-l")
   ga <- g2$grobs[[ia]]
   ax <- ga$children[[2]]
   ax$widths <- rev(ax$widths)
   ax$grobs <- rev(ax$grobs)
   ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
   g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
   g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)

   # draw it
   grid.draw(g)

在此处输入图像描述

于 2013-09-29T19:27:28.003 回答
5

我可能已经找到了放置轴标题的解决方案,其中一些想法来自 Nate Pope 的回答,可以在此处找到:
ggplot2:在绘图顶部添加二次转换的 x 轴
以及有关在 gtable 中访问 grobs 的讨论: https:/ /groups.google.com/forum/m/#!topic/ggplot2-dev/AVHHcYqc5uU

最后,我只是添加了这一行

g <- gtable_add_grob(g, g2$grob[[7]], pp$t, length(g$widths), pp$b)

在打电话之前grid.draw(g),这似乎起到了作用。
据我了解,它采用 y 轴标题g2$grob[[7]]并将其放置在最右侧。它可能不是漂亮的解决方案,但它对我有用。

最后一件事。找到一种旋转轴标题的方法会很好。

问候,

蒂姆

于 2014-02-13T06:16:37.250 回答
4

这个问题已经得到解答,但是在 ggplot 对象的右侧添加辅助轴和辅助比例的一般问题是一直出现的问题。我想在下面报告我自己对这个问题的调整,基于这个线程以及其他几个线程中的各种答案给出的几个元素(请参阅下面的部分参考列表)。

我有批量生产双y轴绘图的需求,所以我构建了一个函数ggplot_dual_axis()。以下是可能感兴趣的功能:

  1. 该代码显示了 y-left 和 y-right 轴的网格线(这是我的主要贡献,尽管它是微不足道的)

  2. 该代码打印一个欧元符号并将其嵌入到 pdf 中(我在那里看到的东西:Plotting Euro Symbol € in ggplot2?

  3. 该代码试图避免打印某些元素两次(“尝试”表明我怀疑它是否完全成功)

未回答的问题:

  • 如果不存在此类几何元素,是否有办法修改ggplot_dual_axis()函数以删除其中一个或任何可能的geom_line()内容geom_point()而不会引发错误。在伪代码中类似于if has(geom_line) ...

  • 如何调用g2$grobs[[7]]by 关键字而不是索引?这就是它返回的结果:text[axis.title.y.text.232]我对这个问题的兴趣源于我通过应用类似技巧来抓取网格线的失败尝试。我认为网格线隐藏在里面的某个地方g2$grobs[[4]],但我不确定如何访问它们。

编辑. 我能够回答自己的问题:如何增加右侧“欧元”标签所在的地块边距?答:theme(plot.margin = unit(c(1,3,0.5,0.8), "lines")) 例如,会成功的。

请指出任何明显的问题或提出改进建议。

现在是代码:希望它对某人有用。正如我所说,我不主张原创性,它是其他人已经展示过的东西的组合。

##' function named ggplot_dual_axis()
##' Takes 2 ggplot plots and makes a dual y-axis plot
##' function takes 2 compulsory arguments and 1 optional argument
##' arg lhs is the ggplot whose y-axis is to be displayed on the left
##' arg rhs is the ggplot whose y-axis is to be displayed on the right
##' arg 'axis.title.y.rhs' takes value "rotate" to rotate right y-axis label
##' The function does as little as possible, namely:
##'  # display the lhs plot without minor grid lines and with a
##'  transparent background to allow grid lines to show
##'  # display the rhs plot without minor grid lines and with a
##'  secondary y axis, a rotated axis label, without minor grid lines
##'  # justify the y-axis label by setting 'hjust = 0' in 'axis.text.y'
##'  # rotate the right plot 'axis.title.y' by 270 degrees, for symmetry
##'  # rotation can be turned off with 'axis.title.y.rhs' option
##'  

ggplot_dual_axis <- function(lhs, rhs, axis.title.y.rhs = "rotate") {
  # 1. Fix the right y-axis label justification
    rhs <- rhs + theme(axis.text.y = element_text(hjust = 0))
  # 2. Rotate the right y-axis label by 270 degrees by default
    if (missing(axis.title.y.rhs) | 
        axis.title.y.rhs %in% c("rotate", "rotated")) {
        rhs <- rhs + theme(axis.title.y = element_text(angle = 270)) 
    }
  # 3a. Use only major grid lines for the left axis
    lhs <- lhs + theme(panel.grid.minor = element_blank())
  # 3b. Use only major grid lines for the right axis
  #     force transparency of the backgrounds to allow grid lines to show
    rhs <- rhs + theme(panel.grid.minor = element_blank(), 
        panel.background = element_rect(fill = "transparent", colour = NA), 
        plot.background = element_rect(fill = "transparent", colour = NA))
# Process gtable objects
  # 4. Extract gtable
    library("gtable") # loads the grid package
    g1 <- ggplot_gtable(ggplot_build(lhs))
    g2 <- ggplot_gtable(ggplot_build(rhs))
  # 5. Overlap the panel of the rhs plot on that of the lhs plot
    pp <- c(subset(g1$layout, name == "panel", se = t:r))
    g <- gtable_add_grob(g1, 
        g2$grobs[[which(g2$layout$name == "panel")]], pp$t, pp$l, pp$b, pp$l)
  # Tweak axis position and labels
    ia <- which(g2$layout$name == "axis-l")
    ga <- g2$grobs[[ia]]
    ax <- ga$children[["axis"]]  # ga$children[[2]]
    ax$widths <- rev(ax$widths)
    ax$grobs <- rev(ax$grobs)
    ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
    g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
    g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)
    g <- gtable_add_grob(g, g2$grobs[[7]], pp$t, length(g$widths), pp$b)
  # Display plot with arrangeGrob wrapper arrangeGrob(g)
    library("gridExtra")
    grid.newpage()
    return(arrangeGrob(g))
}

下面是一些假数据和两个以美元和欧元为单位的图表。如果有一个包可以让你制作一个图并围绕它调用一个双 y 轴图ggplot_dual_axis_er(ggplot_object, currency = c("dollar", "euro")),它会自动为你获取汇率,这不是很酷吗!:-)

# Set directory:
if(.Platform$OS.type == "windows"){
  setwd("c:/R/plots")
} else { 
  setwd("~/R/plots")
}

# Load libraries
library("ggplot2")
library("scales")

# Create euro currency symbol in plot labels, simple version
# avoids loading multiple libraries
# avoids problems with rounding of small numbers, e.g. .0001
labels_euro <- function(x) {# no rounding
paste0("€", format(x, big.mark = ",", decimal.mark = ".", trim = TRUE,
    scientific = FALSE))
} 

labels_dollar <- function(x) {# no rounding: overwrites dollar() of library scales
paste0("$", format(x, big.mark = ",", decimal.mark = ".", trim = TRUE,
    scientific = FALSE))
} 

# Create data
df <- data.frame(
  Year = as.Date(c("2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018"),
    "%Y"), 
  Dollar = c(0, 9000000, 1000000, 8000000, 2000000, 7000000, 3000000, 6000000, 4000000, 5000000, 5000000, 6000000, 4000000, 7000000, 300000, 8000000, 2000000, 9000000))
# set Euro/Dollar exchange rate at 0.8 euros = 1 dollar
df <- cbind(df, Euro = 0.8 * df$Dollar)
# Left y-axis
p1 <- ggplot(data = df, aes(x = Year, y = Dollar)) + 
    geom_line(linestyle = "blank") + # manually remove the line
    theme_bw(20) +                   # make sure font sizes match in both plots
    scale_x_date(labels = date_format("%Y"), breaks = date_breaks("2 years")) + 
    scale_y_continuous(labels = labels_dollar, 
        breaks = seq(from = 0, to = 8000000, by = 2000000))
# Right y-axis
p2 <- ggplot(data = df, aes(x = Year, y = Euro)) + 
    geom_line(color = "blue", linestyle = "dotted", size = 1) + 
    xlab(NULL) +                     # manually remove the label
    theme_bw(20) +                   # make sure font sizes match in both plots
    scale_x_date(labels = date_format("%Y"), breaks = date_breaks("2 years")) +
    scale_y_continuous(labels = labels_euro, 
        breaks = seq(from = 0, to = 7000000, by = 2000000))

# Combine left y-axis with right y-axis
p <- ggplot_dual_axis(lhs = p1, rhs = p2)
p

# Save to PDF
pdf("ggplot-dual-axis-function-test.pdf", 
  encoding = "ISOLatin9.enc", width = 12, height = 8)
p
dev.off()

embedFonts(file = "ggplot-dual-axis-function-test.pdf", 
           outfile = "ggplot-dual-axis-function-test-embedded.pdf")

在此处输入图像描述

部分参考文献列表:

  1. 在 ggplot (R) 上显示两个平行轴
  2. ggplot2中的双y轴用于多面板图
  3. 如何将转换后的比例放在 ggplot2 的右侧?
  4. 使用 grid.arrange 保留图形的比例
  5. 在 ggplot 中对齐图的危险
  6. https://github.com/kohske/ggplot2
于 2014-12-22T18:42:39.583 回答
2

为了旋转轴标题,将以下内容添加到 p2 图中:

p2 <- p2 + theme(axis.title.y=element_text(angle=270))
于 2014-08-03T09:17:55.837 回答