library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(size=4)
假设您有上面的散点图。如何指定那些点的油耗值>= 25 mpg将被绘制为红色,20到25之间的为绿色,0-20之间的为蓝色?这可以在ggplot中实现吗?
aes
内部来实现。这里我将使用 aes
:aes(wt, mpg, color = cut(mpg, breaks = c(0, 20, 25, Inf)))
scale_color_manual(values = c('blue', 'green', 'red'),
limits = c('(0,20]', '(20,25]', '(25,Inf]'))
这指定了要使用哪些颜色(values
),以及为它们分配哪些标签(limits
),这些标签是由cut
生成的分组名称。
综上所述:
ggplot(mtcars) +
aes(wt, mpg, color = cut(mpg, breaks = c(0, 20, 25, Inf))) +
geom_point(size = 4) +
scale_color_manual(values = c('blue', 'green', 'red'),
limits = c('(0,20]', '(20,25]', '(25,Inf]'))
您可以通过将分组作为单独的列添加到您的数据中,或通过提供guides
函数调用来改进图例标题:
guides(color = guide_legend(title = 'mpg range'))
ggplot()
之前与数据框一起处理。你可以像这样使用 ifelse()
:library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(size = 4,
aes(color = ifelse(mpg > 25, "> 25",
ifelse(mpg > 20, "20-25", "< 20")))) +
scale_color_manual(values = c("> 25" = "red", "< 20" = "blue", "20-25" = "green"),
name = "MPG" )
不需要调用 guides()
来创建标题,您可以将它传递给 scale_color_manual()
中的 name = ..
参数。
+ scale_colour_manual(values = c("red" = "red","blue" = "blue","green" = "green"))
以避免 @KonradRudolph 提到的问题。此外,尝试将color
变量创建为数据集列,以便拥有更好的图例/标题。 - AntoniosK