gpt4 book ai didi

r - 使用 scale_colour_brewer 调色板的极值

转载 作者:行者123 更新时间:2023-12-02 00:47:41 25 4
gpt4 key购买 nike

我想用 scale_colour_brewer(palette = "RdYlGn"). 绘制可变数量的列如果我有五列,我得到的最高和最低因素的颜色是深绿色和深红色。

n <- 5 #number of variables
x <- 1:10
y <- runif(10*n)
cond <- rep(1:n, each = 10)
df1 <- data.frame(x,y)

ggplot(df1, aes(x=x, y=y)) +
geom_line(aes(colour=factor(cond), group=factor(cond)),size=2) +
scale_colour_brewer(palette = "RdYlGn") + theme_bw()

enter image description here但是,如果我只有两列 ( n <- 2 ),我会得到范围颜色的中间值。无论我的数据中有多少列,如何获得最高和最低因子的深红色和深绿色?

n <- 2 #number of variables
x <- 1:10
y <- runif(10*n)
cond <- rep(1:n, each = 10)
df1 <- data.frame(x,y)

ggplot(df1, aes(x=x, y=y)) +
geom_line(aes(colour=factor(cond), group=factor(cond)),size=2) +
scale_colour_brewer(palette = "RdYlGn") + theme_bw()

enter image description here

编辑最后,我修改了@paqmo 的答案并使用了 seq .默认情况下,seq选择极值并填充中间值。

n <- 2#number of variables
x <- 1:10
y <- runif(10*n)
cond <- rep(1:n, each = 10)
df1 <- data.frame(x,y)

ggplot(df1, aes(x=x, y=y)) +
geom_line(aes(colour=factor(cond), group=factor(cond)),size=2) +
scale_colour_manual(values = brewer.pal(11,"RdYlGn")[round(seq(from = 1, to = 11,length.out = n))] ) +
theme_bw()

enter image description here

最佳答案

改用 scale_colour_manual 从您想要的调色板中选择哪些值。您必须确保在执行此操作时加载 Rcolorbrewer,因为 ggplot2 仅在您使用 scale_colour_brewer 时调用 Rcolorbrewer > 争论。 colorRampPalette 从 brewer 调色板中获取颜色。

set.seed(1034)
n <- 2 #number of variables
x <- 1:10
y <- runif(10*n)
cond <- rep(1:n, each = 10)
df1 <- data.frame(x,y)

ggplot(df1, aes(x=x, y=y)) +
geom_line(aes(colour=factor(cond), group=factor(cond)),size=2) +
scale_colour_manual(values = colorRampPalette(brewer.pal(11,"RdYlGn"), bias = 2)(n)) +
theme_bw()

enter image description here

 set.seed(1034)
n <- 3 #number of variables
x <- 1:10
y <- runif(10*n)
cond <- rep(1:n, each = 10)
df1 <- data.frame(x,y)

ggplot(df1, aes(x=x, y=y)) +
geom_line(aes(colour=factor(cond), group=factor(cond)),size=2) +
scale_colour_manual(values = colorRampPalette(brewer.pal(11,"RdYlGn"), bias = 2)(n)) +
theme_bw()

enter image description here

 set.seed(1034)
n <- 4 #number of variables
x <- 1:10
y <- runif(10*n)
cond <- rep(1:n, each = 10)
df1 <- data.frame(x,y)

ggplot(df1, aes(x=x, y=y)) +
geom_line(aes(colour=factor(cond), group=factor(cond)),size=2) +
scale_colour_manual(values = colorRampPalette(brewer.pal(11,"RdYlGn"), bias = 2)(n)) +
theme_bw()

enter image description here

关于r - 使用 scale_colour_brewer 调色板的极值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42492009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com