ggplot2簡介:
在2005年開始出現,吸取了基礎繪圖系統和lattice繪圖系統的優點,并利用一個強大的模型來對其進行改進,這一模型基于之前所述的一系列準則,
能夠建立任意類型的統計圖形
1.導入包
library(maps)
library(maptools)
library(rgdal)
library(plyr)
library(MASS)
library(dplyr)
library(ggplot2)
案例1:鑽石資料集
采用ggplot2自帶的鑽石資料集.
資料集變量簡介
## 主要變量
## price 價格
## color 顔色
## carat 重量
## cut 切工
1.1 使用qplot進行簡單的快速作圖
set.seed(123)
# 從整個資料集取出100行進行分析
dsmall <- diamonds[sample(nrow(diamonds), 100), ]
dim(dsmall)
# 1.1.1根據x和y和資料集自動作圖
qplot(carat, price, data = diamonds)
# 1.1.2根據log x和log y和資料集,自動作圖
qplot(log(carat), log(price), data = diamonds)
# 1.1.3根據x和y和資料集按照color進行分類,自動作圖
qplot(carat, price, data = dsmall, colour = color)
# 1.1.4根據x和y和資料集按照shape進行分類,自動作圖
qplot(carat, price, data = dsmall, shape = cut)
# 1.1.5根據x和y和資料集,指定作圖的類型,自動作圖
qplot(carat, price, data = dsmall, geom = c("point", "smooth"))
# 1.1.6根據x和y和資料集,做箱線圖
qplot(cut, price / carat, data = diamonds, geom = "boxplot")
# 1.1.7根據x和y和資料集,做條形圖
qplot(color, data = diamonds, geom = "bar")
# 1.1.8根據x和y和資料集,做直方圖
qplot(carat, data = diamonds, geom = "histogram")
# 1.1.9根據x和y和資料集,做核密度圖
qplot(carat, data = diamonds, geom = "density")
圖 1.1.1 圖 1.1.2 圖 1.1.3
圖 1.1.4 圖 1.1.5 圖 1.1.6
圖 1.1.7 圖 1.1.8 圖1.1.9
1.2使用qplot進行分組
# 1.1.10 使用facets對需要分組的字段進行分組
qplot(carat, data = diamonds, facets = color ~ .,
geom = "histogram", binwidth = 0.1, xlim = c(0, 3))
# 1.1.11 給圖形添加資訊
qplot(
carat, price, data = dsmall,
xlab = "Price ($)", ylab = "Weight (carats)",
main = "Price-weight relationship"
)
圖 1.1.10 按照不同的顔色對重量進行統計 圖 1.1.11 添加和标題,X軸,Y軸解釋
案例2:地圖(不包含中國)
ggplot是基于圖層進行作圖的
df <- data.frame(x = rnorm(2000), y = rnorm(2000))
norm <- ggplot(df, aes(x, y))
norm # 圖層1
norm + geom_point() # 圖層2
# 改變點的大小和形狀
norm + geom_point(shape = 1)
norm + geom_point(shape = ".")
圖層 1 圖層 2 圖層3
采用ggplot2自帶的美國城市資料集us.city
資料集變量簡介
## name 城市名稱
## country.etc 簡稱
## pop 人口數量
## lat 緯度
## lon 經度
## capital 是否是首府
2.1找出美國人口大于500000的城市
big_cities <- subset(us.cities, pop > 500000)
qplot(long, lat, data = big_cities) + borders("state", size = 0.5)
圖 2.1
2.2 做出德州地圖
tx_cities <- subset(us.cities, country.etc == "TX")
# 在使用map做地圖的時候,記住x和y一定指的是經緯度
ggplot(tx_cities, aes(long, lat)) +
borders("county", "texas", colour = "grey70") +
geom_point(colour = alpha("black", 0.5))
圖 2.2 德州地圖
2.3結合USAssert來做出美國各個州的犯罪率
# 從map中擷取洲資料
states <- map_data("state")
# 擷取犯罪資料
arrests <- USArrests
# 将犯罪的資料列名轉換為小寫
names(arrests) <- tolower(names(arrests))
# 擷取根據行名擷取區域資料
arrests$region <- tolower(rownames(USArrests))
# 将兩個資料集進行合并
choro <- merge(states, arrests, by = "region")
# 按犯罪率升序排列
choro <- choro[order(choro$order), ]
# 2.3.1 犯罪率的分布
qplot(long, lat, data = choro, group = group,fill = assault, geom = "polygon")
# 2.3.2 謀殺率的分布
qplot(long, lat, data = choro, group = group,
fill = assault / murder, geom = "polygon")
圖 2.3.1 結論:越往東北犯罪率越低 圖 2.3.2 結論:越往西北謀殺率越低
案例3:中國地圖
3.1 做出各個省份人口的數量
# 載入中國地圖資料集
china=readShapePoly(\'E:\\Udacity\\Data Analysis High\\R\\R_Study\\第一天資料\\bou2_4p.shp\')
# 擷取資料
x<-china@data
# 轉換為datafarme
xs<-data.frame(x,id=seq(0:924)-1)
# 将china轉換為datafarme
shapefile_df <- fortify(china)
# 組合成完整的dataframe
china_mapdata<-join(shapefile_df, xs, type = "full")
# 省份名稱
NAME<-c("北京市","天津市","河北省","山西省","内蒙古自治區","遼甯省","吉林省",
"黑龍江省","上海市","江蘇省","浙江省","安徽省","福建省", "江西省","山東省","河南省",
"湖北省", "湖南省","廣東省", "廣西壯族自治區","海南省", "重慶市","四川省", "貴州省",
"雲南省","***自治區","陝西省","甘肅省","青海省","甯夏回族自治區","******自治區",
"***省","香港特别行政區")
# 各個省份的人口
pop<-c(7355291,3963604,20813492,10654162,8470472,15334912,9162183,13192935,8893483,25635291,20060115,19322432,11971873,11847841,30794664,26404973,
17253385,19029894,32222752,13467663,2451819,10272559,26383458,10745630,
12695396,689521,11084516,7113833,1586635,1945064,6902850,23193638,7026400)
# 組合成完整的d人口-省份的dataframe
pop<-data.frame(NAME,pop)
# 和中國的地圖資訊相結合,組合成datdaframe
china_pop<-join(china_mapdata, pop, type = "full")
ggplot(china_pop, aes(x = long, y = lat, group = group,fill=pop))+
geom_polygon( )+
geom_path(colour = "grey40")
圖3.1 結論顔色越淺的的省份人口越多
3.2 做出上海市的地圖
# 使用subset來取出上海市的資訊
SH<-subset(china_mapdata,NAME=="上海市")
ggplot(SH, aes(x = long, y = lat, group = group,fill=NAME))+
geom_polygon(fill="lightblue" )+
geom_path(colour = "grey40")+
ggtitle("***上海市")+
annotate("text",x=121.4,y=31.15,label="上海市")
圖 3.2
案例4:時間資料
采用ggplot2自帶的economics資料集
資料集變量簡介
## date 時間
## pop 人口
## uempmed 失業率
## unemploy 失業人數
4.1 通過時間檢視失業率
ggplot(aes(x=date,y=uempmed),data=economics)+
geom_line()
圖4.1 圖層1
4.2檢視不同政黨執政時期的失業率
# 擷取失業率的折線圖 圖層1
(unemp <- qplot(date, unemploy, data=economics, geom="line",xlab = "", ylab = "No. unemployed (1000s)"))
# 由于是1970年開始,是以去掉前三行,從尼克松開始統計
presidential1 <- presidential[-(1:3), ]
#确定x和y的邊界
yrng <- range(economics$unemploy)
xrng <- range(economics$date)
# 圖層2
unemp + geom_vline(aes(xintercept = start), data = presidential)
# 圖層3
unemp + geom_rect(aes(NULL, NULL, xmin = start, xmax = end,
fill = party), ymin = yrng[1], ymax = yrng[2],
data = presidential1) + scale_fill_manual(values =
alpha(c("blue", "red"), 0.2))
4.2 圖層2 圖層 3
5.作圖其他設定
5.1 疊加多個圖形
# 美國5大湖之一的休倫湖資料集
huron <- data.frame(year = 1875:1972, level = LakeHuron)
ggplot(huron, aes(year)) +
geom_line(aes(y = level - 5), colour = "blue") +
geom_line(aes(y = level ), colour = "black") +
geom_line(aes(y = level + 5), colour = "red")
圖5.1
5.2 顔色設定
# 使用mtcars資料集
# 制定樂填充色red和邊框色black
ggplot(birthwt, aes(x=bwt)) + geom_histogram(fill="red", colour="black")
# 将cyl轉變為因子
mtcars$cyl <- factor(mtcars$cyl)
# 對不同的ctl進行繪圖
ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point()
圖 5.2.1 圖 5.2.2
5.3 圖例
# 采用的是植物資料集
p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
# 5.3.1 預設的圖例放在右邊
p
# 5.3.2 不使用圖例
p + guides(fill=FALSE)
# 5.3.3 将圖例放在頂部
p + theme(legend.position="top")
# 5.3.4 指定圖例的位置
p + theme(legend.position=c(1,0), legend.justification=c(1,0))
圖 5.3.1 圖 5.3.2
圖 5.3.3 圖 5.4.4
github:https://github.com/Mounment/R-Project