如何用ggplot指定不同的颜色 [英] How to specify different colors with ggplot
问题描述
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(size=4)
假设您具有上面的scatterplot
.您如何指定将>= 25
mpg的点绘制为red
,一个between 20 and 25
green
和0-20
blue
?
Suppose you have the above scatterplot
. How can you specify that the points that are >= 25
mpg will be plotted red
, the one between 20 and 25
green
and the 0-20
blue
?
可以专门使用ggplot
完成吗?
推荐答案
您可以分两个步骤进行操作:
You do this in two steps:
首先,您定义应具有不同颜色的组;通过将另一列添加到数据框或在aes
内部.我将在此处使用aes
First, you define the groups that should have different colours; either by adding another column to the data frame or inside aes
. I’ll use aes
here:
aes(wt, mpg, color = cut(mpg, breaks = c(0, 20, 25, Inf)))
第二,通过指定手动颜色或填充比例:
Secondly, by specifying a manual colour or fill scale:
scale_color_manual(values = c('blue', 'green', 'red'),
limits = c('(0,20]', '(20,25]', '(25,Inf]'))
这指定要使用的颜色(values
)以及将其分配给(limits
)的标签;这些是cut
生成的分组的名称.
This specifies which colours to use (values
) and which labels to assign them to (limits
); these are the names of the grouping generated by 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
函数调用来改善图例标题:
You can improve the legend title by adding the grouping as a separate column to your data, or by providing a guides
function call:
guides(color = guide_legend(title = 'mpg range'))
这篇关于如何用ggplot指定不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!