2014-10-11 106 views
0

我在R中看到了一個繪圖函數的例子,其中「col」參數的值是變量而不是顏色值(例如「blue」,「紅「等)。例如,在下面的示例中,col參數指向變量「Region」,圖形顯示X軸上的Year和Y軸上的Sales,併爲Region(第三維)着色。我檢查了繪圖函數以及顏色參數的文檔,但沒有指出col參數可以採用變量名稱而不是顏色值。我想了解我是否正在查看正確的文檔。在「R」中使用「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)) 
+1

請參閱'?par'和'Color Specification'部分。 – nicola 2014-10-11 05:49:49

+1

@nicola你可以從文檔中複製摘錄並將其作爲答案發布。 – 2014-10-11 05:57:42

+0

@nicola顏色規範不給任何這樣的信息。請閱讀下面的評論。 – KurioZ7 2014-10-11 06:26:47

回答

2

雖然最常用的函數生成中的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. 

注意,在你的情況你是不是傳遞一個charactercol說法,但factor,基本上是一個整數值。此外,您可以指定與您必須繪製的點數相同的顏色,以便您可以聲明每個點的顏色。

希望這會有所幫助。

+0

發佈此問題之前,我已閱讀文檔中的文檔。文檔中的這段文字僅告訴您如何使用顏色值,例如紅色或十六進制代碼等,但它在哪裏提到可以像您在評論文本中提到的那樣傳遞一個因子?像我這樣的學習者如何從閱讀文檔中得知col可以從數據集中獲取一個可能是字段/變量的因子值? – KurioZ7 2014-10-11 06:26:14

+1

我想你提到的是一般的R概念。首先:一個因子被存儲爲一個整數。例如參見:http://www.stat.berkeley.edu/~s133/factors.html。第二:R中的一切都是一個對象。當你指定col =「red」時,你正在創建一個長度爲1,紅色爲'value'的(匿名)字符向量,並將其作爲col參數傳遞。你也可以在'myCol < - 「red」'之前創建一個對象,然後指定'col = myCol'。這基本上就是你在你的問題中所做的。 – nicola 2014-10-11 06:48:35

+0

但在我的示例中,字符向量包含諸如「東」,「西」,「北」,「南」等區域值。它們不是像「紅色」,「藍色」等顏色值!你的意思是說,「東」,「西」等值被轉換爲1和0。如果是這樣,他們如何成爲藍色,紅色等? – KurioZ7 2014-10-11 06:53:13

-1

您必須將(SalesData,plot(year,sales,col = SalesData $ region))「而不是 」與(SalesData,plot(year,sales,col = region))「相加。