【问题标题】:Add text over the bars in text of barplot在 barplot 的文本中的条上添加文本
【发布时间】:2020-03-28 05:31:22
【问题描述】:

我的代码的进步是(MWE):

# https://www.kaggle.com/kaggle/kaggle-survey-2017/data

#### Analisis primario del dataset ####
response <- read.csv(file = "multipleChoiceResponses.csv",na.strings = "")

# seleccionamos solo algunas variables :
Variables <- c("GenderSelect","Country","Age","CurrentJobTitleSelect","MLToolNextYearSelect","LanguageRecommendationSelect","FormalEducation",
               "FirstTrainingSelect","EmployerIndustry")

# Mantenemos en memoria solo las variables seleecionadas : 
response <- response[,Variables]

# Por un tema de cantidades solo nos quedamos con M y F 
Response <- response[response$GenderSelect == "Male" | response$GenderSelect == "Female",]

# agrego una columna para los continenetes (continent) a donde pertenecen los paises (Country)
library(countrycode)
Response$continent <- countrycode(sourcevar = Response[, "Country"],
                                  origin = "country.name",
                                  destination = "continent")

# Convertimos a factor esta nueva variable
Response$continent <- as.factor(Response$continent)


# Eliminamos las filas con elementos NA 
Response <- Response[complete.cases(Response), ]

# Enumeramos todas las filas de manera adecuada
rownames(Response) <- 1:nrow(Response)


Response <- droplevels(Response)


bp_Continent <- barplot(table(Response$continent),
                        main = "Distribucion de DS por continentes",
                        ylim = c(0,3500)
)

# Add GenderSelect proportion by continent  in label argument ("BLABLABLA")
text(x = bp_Continent, y = table(Response$continent), label = "BLABLABLA", pos = 3, cex = 0.8, col = "red")

基本上,脚本加载数据,选择一些变量,创建一个新变量(大陆),最后清理数据。接下来要做的是创建一个条形图,将男性和女性的比例放在条形顶部

我要做的是将“BLABLABLA”更改为按大陆划分的男性和女性之间的比例(GenderSelect 变量)。

我的问题与以下内容完全不同: How to display the frequency at the top of each factor in a barplot in R

因为我感兴趣的是计算比例和条形上方的印象。

【问题讨论】:

标签: r statistics bar-chart kaggle


【解决方案1】:

下面的代码使用了一个最终创建的组合数据集。
一旦计算出比例,只需将它们传递给函数text,参数label

计算比例。

tbl <- table(Response$continent)
xt <- xtabs( ~ GenderSelect + continent, Response)
prop <- sweep(xt, 2, tbl, `/`)

现在绘制条形图。标签是"Male"的比例。

bp_Continent <- barplot(tbl,
                        main = "Distribucion de DS por continentes",
                        ylim = c(0, 3500)
)
text(x = bp_Continent, y = tbl, 
     label = round(prop[2, ], 2), 
     pos = 3, cex = 0.8, col = "red")

其他标签可以是,例如,这些:

sprintf("F: %1.2f/M: %1.2f", prop[1,], prop[2,])

数据创建代码。

set.seed(1234)
n <- 5e3
GenderSelect <- c("Male", "Female")
GenderSelect <- sample(GenderSelect, n, TRUE)
continent <- c("Africa", "Americas", "Asia", "Europa", "Oceania")
continent <- sample(continent, n, TRUE, prob = c(1, 20, 14, 16, 2))
Response <- data.frame(GenderSelect, continent)

【讨论】:

  • 你的代码正是我想学的,我不知道xtabs和sweep的功能
【解决方案2】:

看了Rui的回答,我想到了另一种解决方案。

首先是一个计算男女比例的函数(按大洲),然后是 sapply。

CreaEtiq <- function(conti){
  NumHContin <- dim(Response[Response$GenderSelect=="Male" & Response$continent==conti,])[1]
  NumMACntin <- dim(Response[Response$GenderSelect=="Female" & Response$continent==conti,])[1]
  return(round(NumHContin/NumMACntin,2))
}
EtiquetaBarPlot <- sapply(levels(Response$continent),CreaEtiq)

结束:

bp_Continent <- barplot(table(Response$continent),
                        main = "Distribucion de DS por continentes",
                        ylim = c(0,3500)
)
text(x = bp_Continent, y= table(Response$continent), 
     label = paste("H/M = ", EtiquetaBarPlot) ,
     pos = 3, cex = 0.8, col = "red")

得到下图

【讨论】:

    猜你喜欢
    • 2020-02-25
    • 2021-03-21
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多