R ggplot2-geom_point自定义颜色范围和颜色 [英] R ggplot2 - geom_point custom color ranges and colors
问题描述
我正在尝试通过函数归纳我通常需要的一组图-我无法在其中正确地获取某些方面.
I'm trying to generalize a set of plots I regularly need through a function - I have trouble in getting some aspects right in there.
myCustomScatter <- function(df, col_x, col_y, col_z){
p1 <- ggplot(df, aes(x=df[,col_x]))
p1 <- p1 + geom_point(aes(y=df[,col_y], color=df[,col_z]))
p1 <- p1 + scale_x_continuous(name=colnames(df)[col_x])
p1 <- p1 + scale_y_continuous(name=colnames(df)[col_y])
return(p1)
}
df1 <- data.frame(a=seq(1.1,9.9,1.1), b=seq(0.1,0.9,0.1), c=rev(seq(10.1, 99.9, 11.1)))
myCustomScatter(df1, 1, 2, 3)
这给出了以下预期的图.
This gives the following plot as expected.
-
我需要根据
df [,3]
值离散颜色范围-我需要blue
值> 90,green
表示90> =值> 70,黄色
表示70> =值> 55,orange
表示55> =值> 25&red
的值< = 25-如何指定此值?
I need the color ranges to be discrete based on
df[,3]
values- I needblue
for value > 90,green
for 90 >= value > 70,yellow
for 70 >= value > 55,orange
for 55 >= value > 25 &red
for value <= 25 - how do I specify this ?
我需要图例的标题,而不是 df [,col_z]
是 c
,可以通过 colnames(df1)[3]
-我该如何指定?
I need the title of the legend instead of df[,col_z]
to be c
which I can get through colnames(df1)[3]
- how do I specify this ?
推荐答案
您可以尝试以下操作:
myCustomScatter <- function(df, col_x, col_y, col_z){
p1 <- ggplot(df, aes_string(x=df[,col_x], color = cut(df[,col_z], c(-Inf, 25, 55, 70, 90, Inf))), size = 6)
p1 <- p1 + geom_point(aes_string(y=df[,col_y]))
p1 <- p1 + scale_x_continuous(name=colnames(df)[col_x])
p1 <- p1 + scale_y_continuous(name=colnames(df)[col_y]) # + guides(color=guide_legend('c'))
p1 <- p1 + scale_color_manual(name = names(df)[col_z],
values = c("red",
"orange",
"yellow",
"green",
"blue"))
return(p1)
}
df1 <- data.frame(a=seq(1.1,9.9,1.1), b=seq(0.1,0.9,0.1), c=rev(seq(10.1, 99.9, 11.1)))
myCustomScatter(df1, 1, 2, 3)
这篇关于R ggplot2-geom_point自定义颜色范围和颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!