Расположение столбчатых диаграмм в порядке расположения - PullRequest
1 голос
/ 02 мая 2020

Я пытаюсь расположить столбчатую диаграмму в указанном порядке. Я указал порядок, используя столбец plot_order во фрейме данных, но, похоже, не могу добиться этого порядка. Я хочу, чтобы мой конечный продукт во многом выглядел как ответ на эту проблему: Установите порядок столбчатой ​​диаграммы с накоплением по значению одной из переменных

Как мне добиться порядка переменных x, использующих мои данные.

Мои библиотеки

library(xlsx)
library(RJDBC)
library(sqldf)
library(dplyr)
library(XLConnect)
library(ggplot2)
library(kableExtra)
library(knitr)
library(lubridate)
library(stringr)
library(scales)
library(ggrepel)
library(stats)

Данные:

structure(list(ELEMENT_LABEL = structure(c(4L, 3L, 8L, 1L, 2L, 
7L, 5L, 6L, 1L, 5L, 7L, 2L, 6L, 8L, 3L, 4L, 6L, 5L, 2L, 7L, 1L, 
8L, 3L, 4L, 6L, 5L, 8L, 7L), .Label = c("Lecturers were articulate, enthusiastic and knowledgable.", 
"Objectives and exam content matched closely.", "The objectives were clear.", 
"The module had sufficient illustrations of clinical relevance.", 
"Level of difficulty of exams closely matched that of material presented.", 
"The lectures were clearly presented (slides legible, info load appropriate, not rushed).", 
"The content was well organized.", "The content was integrated across the various disciplines of the module.", 
"Applied Renal Physiology Problem Sets", "Apply the principles of pharmacology to describe the medications used for kidney disease, including drug mechanism of action, adverse effects, and elimination", 
"Apply understanding of the renal system to successfully approach electrolyte disorders and disorders of kidney function", 
"Audience response system", "Correlate the clinical and pathological features of renal disorders", 
"Correlate the clinical symptoms of renal disease with the differential diagnosis", 
"Describe the functional organization of the kidney system at the organ, cellular, and subcellular levels", 
"Describe the major pathophysiologic entities that cause renal diseases and pathological disorders", 
"Did you receive narrative feedback in this module? (written feedback you received about your performance in small group case studies)", 
"For any educational activities you did not rate highly, please explain how they could be improved:", 
"If you would like to provide feedback to a lecturer who was neither among the top two outstanding lecturers or in need of substantial improvement, please select that lecturer below:\n\n(Search by typing lecturer's last name)", 
"In general, how did the technology for the virtual activities within this module work?  Please consider in the context of OVERALL across all activities.....", 
"Lab: Histology Lab", "Labs (e.g., Urinary System Histopath Lab)", 
"Large group discussion: Case Studies (e.g., Interdisciplinary Sepsis Case Study)", 
"Large group discussion: Conferences (e.g., Renal Path Conference)", 
"Lectures", "My small group discussion leader ran effective sessions.", 
"My small group discussion leader understood how their specific sessions fit in with the objectives of the module.", 
"NYU eBooks", "Osmosis videos", "Pathology Lab - Histopath Case-Base Virtual Microscope Lab", 
"Please choose which of the following best represents your pattern of attending lectures:", 
"Please describe the strengths and weaknesses of this module and why you chose the quality rating above:", 
"Please explain your rating of the OSMOSIS videos above - in what ways and/or for which topics did you find the OSMOSIS videos to be useful or not so useful:", 
"Please indicate how useful you found OSMOSIS videos to be in this module:", 
"Please list any topics you had particular difficulty understanding (and explain why difficult):", 
"Please list the main textbooks and reading materials you found most helpful (and feel free to provide feedback on those that you did not find to be useful):", 
"Please provide explanations for your ratings above and/or any additional feedback:", 
"Please rate the overall educational quality of this module.", 
"Please select a lecturer whom you would like to recognize as outstanding.\n\n(Search by typing lecturer's last name.)", 
"Please select another lecturer whom you would like to recognize as outstanding.\n\n(Search by typing lecturer's last name.)", 
"Please select your small group discussion (seminar) leader and provide feedback by indicating how much you agree or disagree with the statements below.  (If you had more than one seminar leader, please choose the one you worked with the most.  If you cannot find the name of your seminar leader, please click N/A).", 
"Please tell us, in terms of technology, what didn't work so well and (please share any ideas you have for how to improve):", 
"Please tell us, in terms of technology, what worked well:", 
"Relate the normal histologic features of the kidneys and urinary tract to their core physiologic functions", 
"Small group discussion (<15): Seminars", "Team-Based Learning (TBMD)", 
"Virtual Microscope - Histopath Lab", "Visit to Dialysis Unit", 
"Was the narrative feedback you received helpful?  Why or why not?", 
"Were there any lecturers you think were in need of substantial improvement? If so, please choose the lecturer:\n\n(Search by typing lecturer's last name)", 
"Were there any other lecturers you think were in need of substantial improvement? If so, please choose the second lecturer:\n\n(Search by typing lecturer's last name)", 
"What about this person's lecture(s) requires substantial improvement?", 
"What feedback do you have for this lecturer?", "What made this lecturer outstanding?"
), class = "factor"), SCALEOPTION_LABEL = structure(c(20L, 20L, 
20L, 20L, 20L, 20L, 20L, 20L, 18L, 18L, 18L, 18L, 18L, 18L, 18L, 
18L, 19L, 19L, 19L, 19L, 19L, 19L, 19L, 19L, 21L, 21L, 21L, 21L
), .Label = c("Completely Met", "Did Not Meet", "Excellent", 
"Fair", "Generally BOTH attended lectures AND listened to taped lectures", 
"Good", "Mix of EITHER attending lectures OR listening to taped lectures (one or the other)", 
"Mostly attended lectures and listened to taped lectures only when needed to clarify", 
"Mostly attended lectures; rarely listened to taped lectures", 
"Mostly listened to taped lectures and rarely attended lectures", 
"No", "Not at all", "Only a little bit", "Partially Met", "Poor", 
"Some problems but OK", "Somewhat", "Somewhat Agree", "Somewhat Disagree", 
"Strongly Agree", "Strongly Disagree", "Very much so", "Worked fine (technology made learning possible)", 
"Worked really well (technology enhanced learning)"), class = "factor"), 
    SCALEOPTION_VALUE = structure(c(4L, 4L, 4L, 4L, 4L, 4L, 4L, 
    4L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 1L, 1L, 1L, 1L), .Label = c("1", "2", "3", "4", "5"
    ), class = "factor"), n = c(105L, 89L, 85L, 76L, 75L, 74L, 
    65L, 60L, 56L, 55L, 54L, 51L, 50L, 48L, 45L, 34L, 27L, 18L, 
    14L, 10L, 8L, 6L, 6L, 1L, 3L, 2L, 1L, 2L), `COUNT(Values)` = c(140L, 
    140L, 140L, 140L, 140L, 140L, 140L, 140L, 140L, 140L, 140L, 
    140L, 140L, 140L, 140L, 140L, 140L, 140L, 140L, 140L, 140L, 
    140L, 140L, 140L, 140L, 140L, 140L, 140L), percentage = c(75, 
    64, 61, 54, 54, 53, 46, 43, 40, 39, 39, 36, 36, 34, 32, 24, 
    19, 13, 10, 7, 6, 4, 4, 1, 2, 1, 1, 1), percentage_title = c("75 %", 
    "64 %", "61 %", "54 %", "54 %", "53 %", "46 %", "43 %", "40 %", 
    "39 %", "39 %", "36 %", "36 %", "34 %", "32 %", "24 %", "19 %", 
    "13 %", "10 %", "7 %", "6 %", "4 %", "4 %", "1 %", "2 %", 
    "1 %", "1 %", "1 %"), cat = structure(c(1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 
    3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("Strongly Agree", 
    "Somewhat Agree", "Somewhat Disagree", "Strongly Disagree", 
    "NA"), class = "factor"), plot_order = structure(1:28, .Label = c("1", 
    "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", 
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", 
    "23", "24", "25", "26", "27", "28"), class = "factor")), row.names = c(NA, 
-28L), class = "data.frame")

И мой код

   scl <- c("Strongly Agree","Somewhat Agree","Somewhat Disagree", "Strongly Disagree", "NA")



ggplot( Data_Table3, aes (x =  reorder(Data_Table3[,1], plot_order), y = Data_Table3[,6], fill = cat)) +
  geom_bar( position = "stack", stat = "identity") +
  scale_fill_discrete( name = "Score") +
  theme(legend.position = "bottom") +
  coord_flip() +
  guides(fill=guide_legend(nrow=2, byrow=TRUE, reverse = TRUE)) +
  scale_x_discrete(labels = wrap_format(50)) + 
  labs( y ="Percentage", x ="Topic", fill=NULL, title= "Title") +
  geom_text(aes(label= percentage_title ), position =position_stack(vjust = 0.5)) 


И что я получаю из этого:

enter image description here

1 Ответ

2 голосов
/ 03 мая 2020

Во-первых, всегда указывайте столбец по имени в aes, а не по [ или $ того же фрейма данных . Во-вторых, вам нужно очистить ваши столбцы, ELEMENT_LABEL и plot_order, перед построением графика.

  • Выполнить droplevels, поскольку ELEMENT_LABEL в настоящее время имеет 54 уровня только для 28 наблюдений! Вероятно, ваш фрейм данных черчения получен из отфильтрованной версии оригинала. После этого вы уменьшите до 8 уровней по 28 наблюдениям.
  • Повторно назначьте значения столбца plot_order уникальными значениями , а не просто целочисленной последовательностью по длине рядов. В частности, plot_order должен упорядочить 8 уникальных значений, соответствующих каждому уникальному вхождению ELEMENT_LABEL. Вы можете достичь этого с помощью встроенного агрегирования, например ave, для вызова min, чтобы получить наименьшее число для того же ELEMENT_LABEL.

После того, как вы очистите эти две колонки, график должен отрегулировать:

Data_Table3 <- within(Data_Table3, {
                         ELEMENT_LABEL <- droplevels(ELEMENT_LABEL)
                         plot_order <- ave(as.integer(as.character(plot_order)), 
                                           ELEMENT_LABEL, FUN=min)
                })

ggplot(Data_Table3, aes (x = reorder(ELEMENT_LABEL, plot_order), 
                         y = percentage, fill = cat)) +
  geom_bar(position = "stack", stat = "identity") +
  scale_fill_discrete(name = "Score") +
  theme(legend.position = "bottom") +
  coord_flip() +
  guides(fill=guide_legend(nrow=2, byrow=TRUE, reverse = TRUE)) +
  scale_x_discrete(labels = wrap_format(50)) + 
  labs( y="Percentage", x="Topic", fill=NULL, title= "Title") +
  geom_text(aes(label=percentage_title), position=position_stack(vjust = 0.5))

Plot Output

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...