Adding one label to each bar graph r

梦想的初衷 提交于 2019-12-05 14:03:49

I recommend to add some sampling. Then the students can't find patterns and make conclusions. Thus, you can try

library(tidyverse)
# bring the data in adequat format
# In brief, a list of the same data.frame for each student
df <- 1:nrow(grades) %>% 
     purrr::map( ~grades) %>% 
     set_names(grades$names) %>% 
     bind_rows(.id = "ID") %>% 
     nest(-ID) %>%  
# the plots using purrr::map2  
     mutate(level=map2(data,ID, ~.x %>% filter(names == .y) %>% select(level))) %>% 
     mutate(data=
           map2(data, ID, ~.x %>% 
                  mutate(n=paste0("#", sample(seq_len(n()), size = n())),
                         names=ifelse(names == .y, as.character(names), n),
                         names=factor(names, levels = c(.y, sample(n, n())))))) %>%
     mutate(plots=map2(data,level, ~ggplot(data=.x,aes(x = names, y = scores, fill = scores))+ 
               geom_col() +
               ggtitle("test scores by level-  February 2018", subtitle = .y$level)
     )) 
# and or illustration purposes the first four plots
library(cowplot)
plot_grid(df$plots[[1]], df$plots[[2]], df$plots[[3]],df$plots[[4]])

It requires a bit of understanding, but we can make it work. As @richardtelford said, we need to manually build the labels, to do so we can 'loop' on the names, filter the by the level of each name, build a vector of appropriate legnth, and finally build the plot with such labels:

names <- c("Jackson", "Smith", "Johnson", "Richards", "Matthews", "Redmond", "Phillips")
scores <- c(.99, .65, .73, .89, .88, .92, .87)
level <- c(10,11,10,11,11,11,11)
grades <- cbind.data.frame(names, scores, level)


library(purrr)
library(dplyr)
library(ggplot2)

grades$names %>% 
  walk(~{
    filtered_grades <- grades %>% 
      filter(level == level[names == .x]) 

    labels <- array(data = '',dim = nrow(filtered_grades))
    labels[filtered_grades$names == as.character(.x)] <- as.character(.x)

    p <- filtered_grades %>% 
      ggplot() +
      geom_col(aes(names, scores, fill = scores)) +
      scale_x_discrete(labels = labels)
      print(p)
  }) 

Created on 2018-05-17 by the reprex package (v0.2.0).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!