在 facet_grid 的每个 free_y 中显示不同的单位
showing different units in each free_y of facet_grid
我用两个不同的 ys(百分比和成本)和相同的 x(年)绘制了两个方面。我从 this post 中汲取了大部分想法以及相同的一些变体。
我想将 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")
谢谢
作为一种脆弱的解决方法,您可以使用
label_fun <- function (x) {
if(max(x, na.rm=TRUE) > 1) dollar(x) else percent(x)
}
(假设你只处理大笔资金和小百分比)
我用两个不同的 ys(百分比和成本)和相同的 x(年)绘制了两个方面。我从 this post 中汲取了大部分想法以及相同的一些变体。 我想将 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")
谢谢
作为一种脆弱的解决方法,您可以使用
label_fun <- function (x) {
if(max(x, na.rm=TRUE) > 1) dollar(x) else percent(x)
}
(假设你只处理大笔资金和小百分比)