2 つの異なる ys (パーセンテージとコスト) と同じ x (年) を使用して、2 つのファセットを重ねてプロットしました。私はこの投稿からほとんどのアイデアと同じもののいくつかのバリエーションを取り入れました. y 軸のラベルをレートのパーセンテージとコストの £ として表示したいのですが、各 y ラベル形式を個別に変更することはできませんでした。
facet_grid を使用した再現可能な例を以下に示します (facet_wrap で同様のものを作成できましたが、同じ問題で立ち往生しています)。
gridExtra パッケージの grid.arrange() を使用することを検討しましたが、凡例に他の問題が発生するようでした。
library(plyr)
library(tidyr)
library(dplyr)
library(ggplot2)
library(scales)
set.seed(12345)
my_labels <- function(variable, value){
names_li <- list("percentage", "cost in pounds")
return(names_li[value])
}
df <- data.frame(
rate = runif(10, 0, 1),
cost = rnorm(10, 100, 40),
years = seq(from = 2001, to = 2010)
)
df %>%
gather(type_of_var,
value,
rate:cost) ->
df2
df2 %>%
ggplot(aes(x = years,
y = value,
ymin = 0,
ymax = .1)) +
facet_grid(type_of_var ~ .,
scales = 'free_y',
labeller = my_labels) +
labs(x = "Year",
y = "") +
geom_point(subset = . (type_of_var == "rate")) +
geom_line(subset = . (type_of_var == "rate"),
colour = "grey") +
## the following two lines don't work
# scale_y_continuous(subset = . (type_of_var == "rate"),
# labels = percent) +
geom_bar(subset = . (type_of_var == "cost"),
stat = "identity") +
theme_bw() +
theme(strip.text.y = element_text(size = 15,
colour = "black"),
plot.title = element_text(lineheight = 0.8,
face = "bold")) +
scale_x_continuous(breaks = seq(2001, 2010, 1)) +
labs(title = "free_y y axis labels")
ありがとう