注:本文案例數據來自於藝恩電影營銷智庫 html
方法一:使用XML
包中的readHTMLTable
函數抓取網頁表格數據。linux
方法二:若是用的是chrome瀏覽器,能夠安裝一個名叫Table Capture的插件,自動抓取網頁表格數據。經過粘貼板或者導入到google的電子表格並下載到本地後,將數據加載到Rchrome
本文使用方法一。在windows中,獲得的數據會出現中文列變量名亂碼(對列變量從新命名就行了,linux不會)。windows
library(XML) library(ggplot2) url <- "http://www.cbooo.cn/year?year=2015" url <- htmlParse(url, encoding="UTF-8")#解析文件,需指定encoding爲"UTF-8",不然亂碼 tables <- readHTMLTable(url) table <- tables[[1]] head(table) 排名:影片名 類型 總票房(萬) 平均票價 場均人次 國家及地區 上映日期 1 1.捉妖記 魔幻 243952 37 42 中國 2015-07-16 2 2.速度與激情7 動做 242655 39 42 美國/日本 2015-04-12 3 3.港囧 喜劇 161336 33 40 中國 2015-09-25 4 4.復仇者聯盟2:奧創紀元 科幻 146438 40 29 美國 2015-05-12 5 5.夏洛特煩惱 喜劇 144145 32 34 中國 2015-09-30 6 6.侏羅紀世界 動做 142066 38 33 美國 2015-06-10
names(table) <- c("title", "type", "boxoffice", "meanprice", "numofpeople", "nation", "date") boxdf <- as.data.frame(lapply(table, as.character), stringsAsFactors=FALSE) boxdf[,1] <- sub(pattern="\\d{1,2}.", replacement="", table[,1]) boxdf <- cbind(rank = 1:25,boxdf) col1 <- c(3,7) col2 <- 4:6 boxdf[, col1] <- lapply(boxdf[,col1], as.factor) boxdf[, col2] <- sapply(boxdf[,col2], as.numeric)
如今,咱們獲得了一個25行8列的電影票房數據框。先查看下結構:瀏覽器
str(boxdf) 'data.frame': 25 obs. of 8 variables: $ rank : int 1 2 3 4 5 6 7 8 9 10 ... $ title : chr "捉妖記" "速度與激情7" "港囧" "復仇者聯盟2:奧創紀元" ... $ type : Factor w/ 8 levels "劇情","動做",..: 8 2 4 7 4 2 5 4 2 3 ... $ boxoffice : num 243952 242655 161336 146438 144145 ... $ meanprice : num 37 39 33 40 32 38 36 33 39 35 ... $ numofpeople: num 42 42 40 29 34 33 45 39 37 34 ... $ nation : Factor w/ 9 levels "中國","中國/中國香港",..: 1 8 1 5 1 5 1 1 1 1 ... $ date : chr "2015-07-16" "2015-04-12" "2015-09-25" "2015-05-12" ...
下面用ggplot2
來可視化電影票房狀況app
ggplot(boxdf)+ geom_bar(aes(x=reorder(title, boxoffice), y=boxoffice, fill = "boxoffice"), position = "dodge",stat = "identity")+ scale_fill_manual(values=c(boxoffice="#A6CEE3")) + coord_flip() + theme(axis.text.x = element_text(size = rel(2)), axis.text.y = element_text(size = rel(2)), plot.title=element_text(vjust=2,size=rel(2)), legend.title = element_text(size = 18)) + labs(x=NULL, y=NULL, title="2015年中國內地電影總票房Top25(單位:萬)")
從下面的條形圖能夠看到觀衆最喜歡的三大電影類型依次是動做、科幻、喜劇。ide
typedata <- as.data.frame(table(boxdf$type)) names(typedata) <- c("type","number") ggplot(typedata, aes(x=type, y =number, fill=type))+ geom_bar(position="dodge", stat="identity")+ geom_text(aes(label=number), hjust=0.5, vjust=-0.5, size=5) + theme(axis.title.x = element_text(colour="black", size=18),axis.text.x = element_text(size = rel(2)), axis.title.y = element_text(colour="black", size=18),axis.text.y = element_text(size = rel(2)), plot.title=element_text(vjust=2,size=rel(2)), legend.title=element_text(size=20)) + labs(x="電影類型",y="影片數", title="2015年中國內地電影票房Top25的電影類型分佈")
本文爲雪晴數據網原創內容,做者溫水根。轉載請註明本文連接http://www.xueqing.cc/cms/article/115 函數