(1)下載可用的PNG文件here,並在工作目錄中保存爲man_woman.png
(2)運行下面的代碼:
library(png)
library(plotly)
genderselection <- read.table(text="
Gender Freq
F 70
M 30
", header=T)
pcts <- round(prop.table(genderselection$Freq)*100)
# Load png file with man and woman
img <- readPNG("man_woman.png")
h <- dim(img)[1]
w <- dim(img)[2]
# Find the rows where feet starts and head ends
pos1 <- which(apply(img[,,1], 1, function(y) any(y==1)))
mn1 <- min(pos1)
mx1 <- max(pos1)
pospctM <- round((mx1-mn1)*pcts[2]/100+mn1)
pospctF <- round((mx1-mn1)*pcts[1]/100+mn1)
# Fill bodies with a different color according to percentages
imgmtx <- img[h:1,,1]
whitemtx <- (imgmtx==1)
colmtx <- matrix(rep(FALSE,h*w),nrow=h)
midpt <- round(w/2)-10
colmtx[mx1:pospctM,1:midpt] <- TRUE
colmtx[mx1:pospctF,(midpt+1):w] <- TRUE
imgmtx[whitemtx & colmtx] <- 0.5
# Plot matrix using heatmap and print text
labs <- c(paste0(pcts[2], "% Males"),paste0(pcts[1], "% Females"))
ax <- list(ticks='', showticklabels=FALSE, showgrid=FALSE, zeroline=FALSE)
p <- plot_ly(z = imgmtx, showscale=FALSE, type='heatmap', width = 500, height = 500) %>%
add_text(x = c(100,250), y = c(20,20), type='heatmap', mode="text",
text=labs, showlegend=FALSE, textfont=list(size=20, color="#FFFFFF"), inherit=FALSE) %>%
layout(xaxis = ax, yaxis = ax)
p
這正是我一直在尋找爲! 謝謝! 有沒有辦法改變背景爲白色和顏色填充? 我確實看到你根據百分比填充了不同顏色的物體,但默認情況下是否填充了顏色?我們可以根據我們的選擇來定義顏色嗎? –
@DollarVora在這裏你可以找到一種方法來控制劇情'heatmap'的調色板:https://stackoverflow.com/questions/44918709/how-to-generate-a-custom-color-scale-for-plotly-熱圖 –