coin_test <- sample(c("head","tail"), #利用sample指令抽取"head"與"tail"字串
size = 200, #抽取200次
replace = TRUE) #取後放回
table(coin_test) #利用table查看coin_test資料
## coin_test
## head tail
## 86 114
co2_total <- c(417.7,541,7706.8,765.6,1591.1,528.6,407.9, #建立co2資料
1098,528.1,443.6,1556.7,438.2,451.2,519.9,5424.5)
names(co2_total) <- c("AUS","CAN","CHN","DEU","IND","IRN","ITA",
"JPN","KOR","MEX","RUS","SAU","ZAF","UK","USA") #命名co2各項名稱
barplot(co2_total, #畫出co2_total資料
xlab = "country", #命名x軸
ylab = "CO2", #命名y軸
main = "Country & CO2 ", #命名標題
cex.name=0.7, #X軸字的大小
col = "green") #挑選顏色
這是在R語言中自行建立資料,且運用命名方式畫出長條圖
我們嘗試利用建立CSV檔來練習讀取,並畫圖。
co2table <- read.csv("D:/CO2table.csv")
barplot(co2table, #畫出co2table長條圖
xlab = "country", #命名x軸
ylab = "CO2", #命名y軸
main = "Country & CO2 ", #命名標題
cex.name=0.7, #X軸字的大小
col = "green") #挑選顏色
## Error in barplot.default(co2table, xlab = "country", ylab = "CO2", main = "Country & CO2 ", : 'height' must be a vector or a matrix
因為讀取的資料,並不是一個向量或矩陣模式,在統計上也可以說不是一個正確的累計次數資料。 所以要對資料進行預處理。
new_co2table <- t(co2table) #轉置資料
barplot(new_co2table[,1], #畫出co2table長條圖,取第一行的資料
xlab = "country", #命名x軸
ylab = "CO2", #命名y軸
main = "Country & CO2 ", #命名標題
cex.name=0.7, #X軸字的大小
col = "green") #挑選顏色
house <- c("re-plastic","re-glase",
"re-paper","plastic","glase","plastic") #建立回收與不回收資料名稱
house_percent <- c(20,34,20,6,10,10) #建立對應資料數值
pie(x=house_percent, #回收與不回收比例資料
main="Pie of Month", #標題名稱
labels =house #個比例名稱
)
這裡我們可以試試看改變數值資料,變成百分比,看看圖形會不會有變化。
house <- c("re-plastic","re-glase",
"re-paper","plastic","glase","plastic") #建立回收與不回收資料名稱
house_percent <- c(0.20,0.34,0.20,0.06,0.10,0.10) #建立對應資料數值
pie(x=house_percent, #回收與不回收比例資料
main="Pie of Month", #標題名稱
labels =house #個比例名稱
)
income <- c(517.1,666.5,991.2,1032,1258.6,
1827.5,2025.2,1880.1,2105,2173.7) #建立收入資料
expenses <- c(590.9,851.9,1143.6,1253.2,
1461.9,1701.9,1789.1,2292.8,3517.7,3818.8) #建立收入資料
plot(income, #畫出收入資料
col="red", #設定顏色
ylim=c(0,4000), #固定Y軸間距
ylab = "dollars") #給Y軸名稱
par(new=TRUE) #可重疊圖片
plot(expenses, #畫出支出資料
col="blue", #設定顏色
ylim=c(0,4000), #固定Y軸間距
ylab = "dollars") #給Y軸名稱
lines(expenses, #連結支出資料的點
col = "blue") #設定顏色
lines(income, #連結收入資料的點
col = "red") #設定顏色
accident <- sample(1:1000, #隨機取出0到1000的資料
10, #抽取10次
replace = FALSE) #取出不放回
hist(accident, #畫出意外事故的直方圖
freq = 10, #將區間以10為單位間隔
col="green" #設定顏色為綠色
)