【问题标题】:ggplot2; single regression line when colour is coded for by a variable?ggplot2;当颜色由变量编码时的单回归线?
【发布时间】:2016-09-17 20:07:55
【问题描述】:

我正在尝试使用一条回归线在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) 

条件是:

condition <- (data.male$survey_type)

即使我将颜色美学移到 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

【问题讨论】:

  • 在geom_smooth() 调用中使用aes(group=1) ...
  • 非常感谢您的工作!知道如何根据调查类型指定颜色吗?
  • 欢迎来到 Stack Overflow!能否请您提供可以为我们提供reproducible example 的数据?
  • 谢谢 Ben,很高兴来到这里 :) !我的实际文件有太多的列和行要放在这里,所以我只是放了一个快照,但包含了绘图所需的所有数据。这是你的意思吗? (对不起,我是一个完整的 R 新手)

标签: r ggplot2 linear-regression


【解决方案1】:
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")
  • 在geom_smooth() 规范中使用aes(group=1) 忽略通过将颜色映射分配给调查类型而引起的按调查类型分组。 (或者,您可以将颜色映射放入 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 ...
  • 出于对色盲人士的礼貌,我建议不要使用原色红色/绿色/蓝色作为您的颜色规格(改用scale_colour_brewer(palette="Dark1"))。

【讨论】:

  • 非常感谢,所有这些都完美运行!我花了几个小时试图自己弄清楚!感谢您提供关于我没想到的颜色的提示:)
  • StackOverflow 弃用 using comments to say "thank you";如果此答案有用,您可以投票(如果您有足够的声誉),并且无论如何如果它令人满意地回答了您的问题,我们鼓励您单击复选标记以接受它。
猜你喜欢
  • 2012-12-18
  • 1970-01-01
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
  • 2014-11-17
  • 1970-01-01
相关资源
最近更新 更多