この質問には回答済みですが、ggplot オブジェクトの右側に 2 次軸と 2 次スケールを追加するという一般的な問題は、常に発生する問題です。このスレッドと他のいくつかのスレッドのさまざまな回答によって与えられたいくつかの要素に基づいて、問題に関する私自身の微調整を以下に報告したいと思います(以下の参照の部分的なリストを参照)。
デュアル y 軸プロットを大量生産する必要があるため、関数を作成しましたggplot_dual_axis()
。潜在的に興味深い機能は次のとおりです。
コードは、y-left 軸と y-right 軸の両方のグリッド線を表示します(これは些細なことですが、私の主な貢献です)
コードはユーロ記号を出力し、それを pdf に埋め込みます(そこで見たもの: ggplot2 でユーロ記号 € をプロットしていますか? )
コードは、特定の要素を 2 回出力することを回避しようとします (「試行」は、完全に成功するかどうか疑わしいことを示唆しています)
未回答の質問:
そのような geom 要素が存在しない場合、エラーをスローせずに、またはそのいずれかggplot_dual_axis()
を削除するように関数を変更する方法はありますか。次のような疑似コードでgeom_line()
geom_point()
if has(geom_line) ...
g2$grobs[[7]]
index ではなく 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))
}
そして、いくつかの偽のデータと、ドルとユーロの単位であることが意図されている 2 つのプロットの下にあります。1 つのプロットを作成し、そのようにデュアル 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")

参考文献の部分的なリスト:
- ggplot に 2 つの平行な軸を表示する (R)
- 複数パネル図のggplot2の二重y軸
- ggplot2の右側に変換されたスケールを配置するにはどうすればよいですか?
- grid.arrange を使用してグラフの割合を維持する
- ggplot でプロットを整列させる危険性
- https://github.com/kohske/ggplot2