【问题标题】:usage of "col" parameter Plot function in RR中“col”参数绘图函数的使用
【发布时间】:2014-12-06 08:01:30
【问题描述】:

我在 R 中看到了一个绘图函数示例,其中“col”参数的值是一个变量而不是颜色值(例如“blue”、“red”等)。例如,在下面的示例中,col 参数指向变量“Region”,该图在 X 轴上显示 Year,在 Y 轴上显示 Sales,点为 Region(第三维)着色。我检查了绘图函数和颜色参数的文档,但没有迹象表明 col 参数可以采用变量名称而不是颜色值。我想了解我是否正在查看正确的文档。

year = c(1990:1994)

sales = c(1:5)

region = c('East','East','West','North','South')

SalesData = data.frame(sales,year,region)   

with(SalesData,plot(year,sales,col=region))

【问题讨论】:

  • ?parColor Specification部分。
  • @nicola 您可以从文档中复制摘录并将其作为答案发布。
  • @nicola 颜色规范没有提供任何此类信息。请阅读下面我的评论。

标签: r


【解决方案1】:

虽然在 R 中生成绘图的最常用函数是 plot,但您可以在 ?par 文档下找到最有用的信息。其中有一个Color Specification 部分,描述了如何为绘图设置颜色。这里摘录:

 Colors can be specified in several different ways. The simplest
 way is with a character string giving the color name (e.g.,
 ‘"red"’).  A list of the possible colors can be obtained with the
 function ‘colors’.  Alternatively, colors can be specified
 directly in terms of their RGB components with a string of the
 form ‘"#RRGGBB"’ where each of the pairs ‘RR’, ‘GG’, ‘BB’ consist
 of two hexadecimal digits giving a value in the range ‘00’ to
 ‘FF’.  Colors can also be specified by giving an index into a
 small table of colors, the ‘palette’: indices wrap round so with
 the default palette of size 8, ‘10’ is the same as ‘2’.  This
 provides compatibility with S.  Index ‘0’ corresponds to the
 background color.  Note that the palette (apart from ‘0’ which is
 per-device) is a per-session setting.

请注意,在您的情况下,您不是将character 传递给col 参数,而是将factor 传递给基本上是一个整数值。此外,您可以指定与必须绘制的点一样多的颜色,因此您可以声明每个点的颜色。

希望这会有所帮助。

【讨论】:

  • 在发布此问题之前,我已在文档中阅读此文本。文档中的此文本仅告诉您有关使用红色或十六进制代码等颜色值的信息,但它在哪里提到可以传递您在评论文本中提到的因素?像我这样的学习者如何通过阅读文档知道 col 可以从数据集中获取一个可能是字段/变量的因子值?
  • 我猜你提到的是一般的 R 概念。首先:一个因子被存储为一个整数。例如:stat.berkeley.edu/~s133/factors.html。第二:R 中的一切都是对象。当您指定 col="red" 时,您正在创建一个长度为 1 的(匿名)character 向量,red 作为值并将其作为 col 参数传递。您也可以在之前创建一个对象:myCol<-"red",然后指定col=myCol。这基本上就是您在问题中所做的。
  • 但在我的示例中,字符向量包含区域值,例如“East”、“West”、“North”、“South”。它们不是“红色”、“蓝色”等颜色值!您的意思是说“东”、“西”等值被转换为 1 和 0。如果是这样,它们如何变成蓝色、红色等?
  • 同样,region 不是character 向量,而是factor。您传递的是整数值。您的电话与col=c(1,1,2,3,4) 相同。您是否阅读了我在上一条评论中提供的链接?
  • Color Specification 部分还解释了默认的palette 采用颜色索引。尝试palette() 获取默认值并阅读?palette
【解决方案2】:

如果您正在制作各种图表,请查看http://coleoguy.blogspot.de/2016/06/symbols-and-colors-in-r-pch-argument.html

有一个选择颜色的工具:http://colorbrewer2.org/

请记住,当您在 HEX 中输入一系列颜色时,请确保使用大写字母:例如col=c("#1B9E77","#D95F02","#7570B3","#666666")

【讨论】:

    【解决方案3】:

    您必须输入“with(SalesData,plot(year,sales,col=SalesData$region))”而不是 "with(SalesData,plot(year,sales,col=region))"。

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 2013-06-20
      • 2014-07-10
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      相关资源
      最近更新 更多