ggplot2; 当颜色由变量编码时的单回归线?

Nad*_*iah 6 r linear-regression ggplot2

我试图ggplot2用一条回归线创建一个散点图,即使颜色取决于“调查类型”变量。理想情况下,我还想指定哪种调查类型是哪种颜色(社区 = 红色,国家以下地区 = 绿色,国家 = 蓝色)。

这是我正在运行的代码,它目前为我提供了 3 条独立的回归线,每种调查类型都有一条。

ggplot(data=data.male,aes(x=mid_year, y=mean_tc, colour =condition)) +
geom_point(shape=1) + 
geom_smooth(method=lm, data=data.male, na.rm = TRUE, fullrange= TRUE) 
Run Code Online (Sandbox Code Playgroud)

条件是:

condition <- (data.male$survey_type)
Run Code Online (Sandbox Code Playgroud)

即使我将颜色美学移到 geom_point 函数它也不起作用,因为它给我一个错误,说社区不是一个有效的颜色名称?

我的实际数据文件非常大,所以我在这里只给出一个小样本:

data.male 数据集:

mid_year mean_tc survey_type
2000     4       Community
2001     5       National
2002     5.1     Subnational
2003     4.3     National
2004     4.5     Community
2005     5.2     Subnational
2006     4.4     National
Run Code Online (Sandbox Code Playgroud)

Ben*_*ker 7

data.male <- read.table(header=TRUE,text="
 mid_year mean_tc survey_type
 2000     4       Community
 2001     5       National
 2002     5.1     Subnational
 2003     4.3     National
 2004     4.5     Community
 2005     5.2     Subnational
 2006     4.4     National")
Run Code Online (Sandbox Code Playgroud)
  • aes(group=1)geom_smooth()规范中使用以忽略通过将颜色映射分配给调查类型而引起的按调查类型分组。(或者,您可以将颜色映射放入geom_point()而不是整体ggplot()规范中。)
  • 如果要指定颜色,则需要将其作为数据框中变量的名称(即survey_type);如果您想将图例中的名称更改为condition您可以在色标规范中执行此操作(下面的示例)。
library(ggplot2); theme_set(theme_bw())
ggplot(data=data.male,aes(x=mid_year, y=mean_tc, colour=survey_type)) +
   geom_point(shape=1) +
   ## use aes(group=1) for single regression line across groups;
   ##   don't need to re-specify data argument
   ##  set colour to black (from default blue) to avoid confusion
   ##  with national (blue) points
   geom_smooth(method=lm, na.rm = TRUE, fullrange= TRUE,
               aes(group=1),colour="black")+
   scale_colour_manual(name="condition",
       values=c("red","blue","green"))
       ## in factor level order; probably better to
       ## specify 'breaks' explicitly ...
Run Code Online (Sandbox Code Playgroud)
  • 出于对色盲人士的礼貌,我建议不要使用主要的红色/绿色/蓝色作为您的颜色规格(请尝试scale_colour_brewer(palette="Dark1"))。

在此处输入图片说明