[英]Free colour scales in facet_grid
Say I have the following data frame:假设我有以下数据框:
# Set seed for RNG
set.seed(33550336)
# Create toy data frame
loc_x <- c(a = 1, b = 2, c = 3)
loc_y <- c(a = 3, b = 2, c = 1)
scaling <- c(temp = 100, sal = 10, chl = 1)
df <- expand.grid(loc_name = letters[1:3],
variables = c("temp", "sal", "chl"),
season = c("spring", "autumn")) %>%
mutate(loc_x = loc_x[loc_name],
loc_y = loc_y[loc_name],
value = runif(nrow(.)),
value = value * scaling[variables])
which looks like,看起来像,
# > head(df)
# loc_name variables season loc_x loc_y value
# 1 a temp spring 1 3 86.364697
# 2 b temp spring 2 2 35.222573
# 3 c temp spring 3 1 52.574082
# 4 a sal spring 1 3 0.667227
# 5 b sal spring 2 2 3.751383
# 6 c sal spring 3 1 9.197086
I want to plot these data in a facet grid using variables
and season
to define panels, like this:我想使用
variables
和season
在分面网格中绘制这些数据来定义面板,如下所示:
g <- ggplot(df) + geom_point(aes(x = loc_name, y = value), size = 5)
g <- g + facet_grid(variables ~ season)
g
As you can see, different variables
have very different scales.如您所见,不同的
variables
具有非常不同的尺度。 So, I use scales = "free"
to account for this.所以,我使用
scales = "free"
来解决这个问题。
g <- ggplot(df) + geom_point(aes(x = loc_name, y = value), size = 5)
g <- g + facet_grid(variables ~ season, scales = "free")
g
Mucho convenient.多方便。 Now, say I want to do this, but plot the points by
loc_x
and loc_y
and have value
represented by colour instead of y position:现在,假设我想这样做,但是通过
loc_x
和loc_y
绘制点,并用颜色而不是 y 位置表示value
:
g <- ggplot(df) + geom_point(aes(x = loc_x, y = loc_y, colour = value),
size = 5)
g <- g + facet_grid(variables ~ season, scales = "free")
g <- g + scale_colour_gradient2(low = "#3366CC",
mid = "white",
high = "#FF3300",
midpoint = 50)
g
Notice that the colour scales are not free and, like the first figure, values for sal
and chl
cannot be read easily.请注意,色标不是自由的,并且与第一个图一样,
sal
和chl
值不容易读取。
My question: is it possible to do an equivalent of scales = "free"
but for colour, so that each row (in this case) has a separate colour bar?我的问题:是否可以做等效的
scales = "free"
但对于颜色,以便每一行(在这种情况下)都有一个单独的颜色条? Or, do I have to plot each variable (ie, row in the figure) and patch them together using something like cowplot
?或者,我是否必须绘制每个变量(即图中的行)并使用诸如
cowplot
东西将它们拼凑在一起?
Using the development version of dplyr
:使用
dplyr
的开发版本:
library(dplyr)
library(purrr)
library(ggplot2)
library(cowplot)
df %>%
group_split(variables, season) %>%
map(
~ggplot(., aes(loc_x, loc_y, color = value)) +
geom_point(size = 5) +
scale_colour_gradient2(
low = "#3366CC",
mid = "white",
high = "#FF3300",
midpoint = median(.$value)
) +
facet_grid(~ variables + season, labeller = function(x) label_value(x, multi_line = FALSE))
) %>%
plot_grid(plotlist = ., align = 'hv', ncol = 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.