R語言:畫樹圖

Hellolijunshy發表於2018-09-22

原始資料長這樣:

“iyear”表示年份;“nkill”表示死亡人數;“region”表示地區;“總計”表示某年份死亡總人數;nkii裡的缺失資料自動按“0”運算。

資料儲存在名為“ljs”的csv格式裡。

 

應提前下載好treemap包,先介紹treemap函式的用法:

treemap(dtf, index, vSize, vColor = NULL, stdErr = NULL...)
dtf :a data.frame. Required.

index:  
        vector of column names in dtf that specify the aggregation indices. It could contain only one column name, which results in a treemap without hierarchy. If multiple column names are provided, the first name is the highest aggregation level, the second name the second-highest aggregation level, and so on. Required.

(指定聚合索引的dtf中列名的向量。它只能包含一個列名,這會導致一個沒有層次結構的treemap。如果提供了多個列名,則第一個列名是最高的聚合級別,第二個列名是次高聚合級別,依此類推。必需的。)

vSize :name of the column in dtf that specifies the sizes of the rectangles. Required. (指定矩形大小的dtf列的名稱。)

vColor :name of the column that, in combination with type, determines the colors of the rectangles. The variable can be scaled by the addition of "*<scale factor>" or "/<scale factor>". Note: when omitted for "value" treemaps, a contant value of 1 is taken.(與型別組合確定矩形顏色的列的名稱。可以通過新增“*”或“/”來縮放變數。注意:當忽略“值”樹地圖時,將取1。)

(1)按年份畫樹圖:

mydata<-read.table("ljs.csv",header=TRUE,sep=",")
library(dplyr)
library(treemap)
treemap(mydata,index=c("iyear"),vSize = "nkill",title = "全球恐怖襲擊地區(年份)死亡數")

輸出結果:

(2)按地區畫數圖:

mydata<-read.table("ljs.csv",header=TRUE,sep=",")
library(dplyr)
library(treemap)
treemap(mydata,index=c("region"),vSize = "nkill",title = "全球恐怖襲擊地區死亡數")
#將index裡的“iyear”換成“region”即可

輸出結果:(按地區統計死亡人數並畫圖)

(3)按年份和地區(index裡“先地區後年份”)畫圖:

mydata<-read.table("ljs.csv",header=TRUE,sep=",")
library(dplyr)
library(treemap)
treemap(mydata,index=c("region","iyear"),vSize = "nkill",title = "全球恐怖襲擊地區死亡數")

輸出結果:

(4)按年份和地區(index裡“先年份後地區”)畫圖:

mydata<-read.table("ljs.csv",header=TRUE,sep=",")
library(dplyr)
library(treemap)
treemap(mydata,index=c("iyear","region"),vSize = "nkill",title = "全球恐怖襲擊地區死亡數")

 輸出結果:

2004年份裡Southeast Asia有3人,South Asia有1人。

相關文章