我这里有一些代码将使用 colorRampPalette() 和 scale_color_gradientn() 为沿限制范围的点着色。
Colors <- colorRampPalette(c("beige", "darkolivegreen1","green","aquamarine", "darkcyan",
"dodgerblue4", "purple4", "magenta3", "pink"))
Colors_range <- Colors(50)
ggplot(iris, aes(x = Petal.Width, y = Petal.Length, color = Petal.Length)) +
geom_point() +
facet_wrap(~ Species, scales = "free_y") +
scale_color_gradientn(colors = Colors_range, limits = c(0,7))
我希望有一种方法可以适应这种情况,以连续为 y 或 x 轴而不是点着色。我可以用 axis.line.y 做一种纯色
ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) +
geom_point() +
facet_wrap(~ Species, scales = "free_y") +
theme(axis.line.y = element_line(size = 3, color = "green", linetype=1))
我看到了一种以某种方式使用 geom_vline 的潜在方法,但更喜欢 axis.line.y ,因为它根本不会改变绘图。
ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) +
geom_point() +
facet_wrap(~ Species, scales = "free_y") +
geom_vline(xintercept = -0.1, color = "green", size = 3)
不知道获取渐变彩色轴线的选项。相反,如果您想伪造轴线,那么一种选择是使用
ggforce::geom_link2
,我通过 coord_cartesian
设置限制:
library(ggplot2)
library(ggforce)
ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) +
geom_point() +
geom_link2(
aes(color = Petal.Length, x = 0),
linewidth = 1
) +
facet_wrap(~Species, scales = "free_y") +
coord_cartesian(clip = "off", xlim = range(iris$Petal.Width)) +
scale_color_gradientn(colors = Colors_range, limits = c(0, 7))
第二个选择是使用
geom_line
,但这需要一些额外的数据整理:
dat_line <- iris |>
split(~Species) |>
lapply(\(x) {
data.frame(
Species = unique(x$Species),
Petal.Width = 0,
Petal.Length = seq(
min(x$Petal.Length), max(x$Petal.Length),
length.out = 100
)
)
}) |>
dplyr::bind_rows()
ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) +
geom_point() +
geom_line(
data = dat_line,
aes(color = Petal.Length),
linewidth = 1
) +
facet_wrap(~Species, scales = "free_y") +
coord_cartesian(clip = "off", xlim = range(iris$Petal.Width)) +
scale_color_gradientn(colors = Colors_range, limits = c(0, 7))