Переименование переменных по оси X для разделения данных текущего месяца и данных предыдущего месяца

#r #ggplot2

#r #ggplot2

Вопрос:

Привет, ребята, у меня есть данные больницы, которые выглядят следующим образом;

 
hospitals <- c('Johnd Hospital','Johnd Hospital','Jolie Hope Hospital','Jolie Hope Hospital','Hope Hospital','Hope Hospital')
variables <- c('temperature', 'temperature', 'pulse rate','pulse rate', 'resp rate', 'resp rate')
score <- c(92,82,63,78, 23, 59)
months <- c('october', 'september', 'october', 'september', 'october', 'september')

datat <- data.frame(hospitals, variables, score, months)

datat$colour <- ifelse(datat$score >=90, "seagreen3", 
                           ifelse(datat$score > 80 amp; datat$score <= 89, "gold1",
                                  ifelse(datat$score > 60 amp; datat$score <= 79, "plum2", "red3")))
#performance scores
datat$perfomance <- ifelse(as.numeric(datat$score) >=90, "Excellent Perfomance (>=90)%", 
                               ifelse(as.numeric(datat$score) >= 80 amp; as.numeric(datat$score) <= 89, "Good Perfomance (80-89)%",
                                      ifelse(as.numeric(datat$score) > 60 amp; as.numeric(datat$score) <= 79, "Some Perfomance (60-79)%", "Poor Perfomance (<60)%")))

nam = c("Good Perfomance (80-89)%", "Some Perfomance (60-79)%", "Poor Perfomance (<60)%", "Excellent Perfomance (>=90)%")
grays = c("gold1", "plum2", "red3", "seagreen3")

my_color <- setNames(grays, nam)
my_color
 

Теперь по этим данным я хочу построить график производительности переменных за текущий месяц и предыдущий месяц. До сих пор я могу визуализировать гистограмму уклонения для переменной оценки за текущий месяц и за прошлый месяц. примером может служить переменная, такая как температура, для которой у меня есть два столбца за этот месяц и за прошлый месяц.
Вот как я визуализировал

 myplott <- function(datat, hospital) {
  
  print(paste0("Plot for hospital: ", hospital))
  
  p <- ggplot(datat%>% filter(hospitals == hospital), 
              aes(x = variables, y = as.numeric(score)))  
    #facet_grid(cols = vars(Group), scales = "free", space = "free")  
    geom_bar(position = "dodge2", stat = "identity")  
    theme_bw()  
    ylab("Percentage %")  
    scale_y_continuous(breaks = seq(-10, 100, by = 10))  
    ggtitle(hospital)  
    labs(caption = "Please note; -5 (red paint below 0) indicates 0% documentation for that indicator")  
    ### use manual color here
    scale_fill_manual(values = my_color)  
    
    theme(axis.text.x = element_text(size = 13, hjust = 1, angle = 45))  
    geom_hline(yintercept = 90, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 80, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 60, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 0, linetype = "dashed", color = "black", size = 0.5)  
    #geom_text(aes(label = value), vjust = 0, color = "black", size = 2.8)  
    theme(plot.title = element_text(face = "bold", hjust = 0.5, size = 20), legend.position = "top")  
    #theme(plot.subtitle.title = element_text('Admission and during admission vitals monitored'))  
    theme(legend.title = element_blank())
  
  return(p)
  
}
myplott(comb.data, "Jolie Hope Hospital")

 

Сейчас моя проблема заключается в том, как назвать столбцы на оси X, чтобы человек мог знать столбик за предыдущий месяц и текущий месяц, например, назвать температуру как температуру (октябрь) и температуру (ноябрь). Конечным результатом является переименование переменных оценок за текущий месяц и предыдущий месяц по оси X.Если кто-нибудь знает, как я могу назвать столбцы на оси X, пожалуйста, помогите. Спасибо

Ответ №1:

Одним из способов может быть использование interaction() :

 library(ggplot2)
#Function
myplott <- function(datat, hospital) {
  
  print(paste0("Plot for hospital: ", hospital))
  
  p <- ggplot(datat%>% filter(hospitals == hospital), 
              aes(x = interaction(variables,months), y = as.numeric(score)))  
    #facet_grid(cols = vars(Group), scales = "free", space = "free")  
    geom_bar(position = "dodge2", stat = "identity")  
    theme_bw()  
    ylab("Percentage %")  
    scale_y_continuous(breaks = seq(-10, 100, by = 10))  
    ggtitle(hospital)  
    labs(caption = "Please note; -5 (red paint below 0) indicates 0% documentation for that indicator")  
    ### use manual color here
    scale_fill_manual(values = my_color)  
    #geom_text(aes(label=months),position = position_dodge2(0.9),vjust=-0.5) 
    theme(axis.text.x = element_text(size = 13, hjust = 1, angle = 45))  
    geom_hline(yintercept = 90, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 80, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 60, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 0, linetype = "dashed", color = "black", size = 0.5)  
    theme(plot.title = element_text(face = "bold", hjust = 0.5, size = 20), legend.position = "top")  
    #theme(plot.subtitle.title = element_text('Admission and during admission vitals monitored'))  
    theme(legend.title = element_blank()) 
    xlab('')
  
  return(p)
  
}
#Apply
myplott(datat, "Jolie Hope Hospital")
 

Выходной сигнал:

введите описание изображения здесь

Или, с моей точки зрения, самый элегантный:

 #Function 2
myplott <- function(datat, hospital) {
  
  print(paste0("Plot for hospital: ", hospital))
  
  p <- ggplot(datat%>% filter(hospitals == hospital), 
              aes(x = variables, y = as.numeric(score)))  
    #facet_grid(cols = vars(Group), scales = "free", space = "free")  
    geom_bar(position = "dodge2", stat = "identity")  
    theme_bw()  
    ylab("Percentage %")  
    scale_y_continuous(breaks = seq(-10, 100, by = 10))  
    ggtitle(hospital)  
    labs(caption = "Please note; -5 (red paint below 0) indicates 0% documentation for that indicator")  
    ### use manual color here
    scale_fill_manual(values = my_color)  
    geom_text(aes(label=months),position = position_dodge2(0.9),vjust=-0.5) 
    theme(axis.text.x = element_text(size = 13, hjust = 1, angle = 45))  
    geom_hline(yintercept = 90, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 80, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 60, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 0, linetype = "dashed", color = "black", size = 0.5)  
    theme(plot.title = element_text(face = "bold", hjust = 0.5, size = 20), legend.position = "top")  
    #theme(plot.subtitle.title = element_text('Admission and during admission vitals monitored'))  
    theme(legend.title = element_blank()) 
    xlab('')
  
  return(p)
  
}
#Apply
myplott(datat, "Jolie Hope Hospital")
 

Выходной сигнал:

введите описание изображения здесь

Обновить:

 #Function 3
myplott <- function(datat, hospital) {
  
  print(paste0("Plot for hospital: ", hospital))
  
  p <- ggplot(datat%>% filter(hospitals == hospital), 
              aes(x = variables, y = as.numeric(score),fill=months))  
    #facet_grid(cols = vars(Group), scales = "free", space = "free")  
    geom_bar(position = "dodge2", stat = "identity")  
    theme_bw()  
    ylab("Percentage %")  
    scale_y_continuous(breaks = seq(-10, 100, by = 10))  
    ggtitle(hospital)  
    labs(caption = "Please note; -5 (red paint below 0) indicates 0% documentation for that indicator")  
    ### use manual color here
    #scale_fill_manual(values = my_color)  
    # geom_text(aes(label=months),position = position_dodge2(0.9),vjust=-0.5) 
    theme(axis.text.x = element_text(size = 13, hjust = 1, angle = 45))  
    geom_hline(yintercept = 90, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 80, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 60, linetype = "dashed", color = "black", size = 0.5)  
    geom_hline(yintercept = 0, linetype = "dashed", color = "black", size = 0.5)  
    theme(plot.title = element_text(face = "bold", hjust = 0.5, size = 20), legend.position = "top")  
    #theme(plot.subtitle.title = element_text('Admission and during admission vitals monitored'))  
    theme(legend.title = element_blank()) 
    xlab('')
  
  return(p)
  
}
#Apply
myplott(datat, "Jolie Hope Hospital")
 

Выходной сигнал:

введите описание изображения здесь

Комментарии:

1. Спасибо вам за это… Я бы хотел использовать interaction , но я заметил, что он упорядочивает имена в алфавитном порядке, возможно ли, чтобы переменная с двумя столбцами находилась рядом друг с другом для сравнения?

2. @LivingstoneM Я могу изменить код, чтобы сохранить столбцы, но заполнять по месяцам? Вы согласны с этим?

3. @LivingstoneM Я добавил обновление, дайте мне знать, если вас это устраивает