這邊用iris做說明,主要就是用n分位距來畫長調圖的一個function,
變數部分:
hist_ggplot2(你要放入的dataframe , 你要分割的數值型資料,你要分類的類別變數,你要分幾級距)
hist_ggplot2 = function(iris , k , l , i ){
packages = c("ggplot2")
existing = as.character(installed.packages()[,1])
for(pkg in packages[!(packages %in% existing)]) install.packages(pkg)
library(ggplot2)
target = iris[,k]
target_2 = iris[,l]
quantile_1 = 0
for(j in 1:i)
quantile_1[j+1] = quantile(target,j*0.1)
quantile_2 = target
for(j in 1:i)
quantile_2 = ifelse(target > quantile_1[j] & target <= quantile_1[j+1] , j %>% as.character() , quantile_2)
new_data.frame = data.frame(target = target,y = as.factor(target_2),change = as.numeric(quantile_2))
ggplot(new_data.frame, aes(x = change, fill = y)) +
geom_bar(position = "identity") +
theme_classic(base_size = 16) +
scale_x_continuous(breaks = c(1:(i+1)) ,labels =quantile_1)
}
hist_ggplot2(iris,3,5,10)
這邊填入iris第三行用第五行來分類然後分十類,就可以得到想要的圖片啦!