Facet wrap of a lollipop plot

一世执手 提交于 2021-02-11 12:49:35

问题


I'm trying to make multiple lollipop plots using a facet wrap, like in the third code block / example and picture below on this page.

However, I can't get the code example to work. Can you please help me see where it is written incorrectly (if at all)?

The data:

set.seed(1)
data <-as.data.frame(matrix( sample( 2:20 , 40 , replace=T) , ncol=10))
colnames(data) <- c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" )
data <-rbind(rep(20,10) , rep(0,10) , data)
rownames(data) <- c("-", "--", "John", "Angli", "Baptiste", "Alfred")

When I run the code to plot it:

# Barplot
data <- data %>% slice(c(3:6)) %>% 
  t() %>% 
  as.data.frame() %>% 
  add_rownames() %>% 
  arrange(V1) %>% 
  mutate(rowname=factor(rowname, rowname)) %>% 
  gather(key=name, value=mark, -1)

#Recode
data$name <- recode(data$name, V1 = "John", V2 = "Angli", V3 = "Baptiste", V4 = "Alfred")

# Plot
data %>% ggplot( aes(x=rowname, y=mark)) +
    geom_bar(stat="identity", fill="#69b3a2", width=0.6) +
    coord_flip() +
    theme_ipsum() +
    theme(
      panel.grid.minor.y = element_blank(),
      panel.grid.major.y = element_blank(),
      axis.text = element_text( size=48 )
    ) +
    ylim(0,20) +
    ylab("mark") +
    xlab("") +
    facet_wrap(~name, ncol=4)

I get the following error:

Error in order(V1) : object 'V1' not found

The first two code blocks on the linked page rely on two column tibbles, so I think the first vector automatically gets named V1. But it's not clear to me how to fix this example code, since the columns are named already. I hope this question is clear.


回答1:


The column names do remain intact so you don't have V1, V2 columns there. Also you can replace gather with pivot_longer. Try :

library(tidyverse)

data <- data %>% 
  slice(3:6) %>% 
  t()  %>%
  as.data.frame() %>%
  add_rownames() %>%
  mutate(rowname=factor(rowname, rowname)) %>% 
  pivot_longer(cols = -1, values_to = 'mark')



data %>% ggplot( aes(x=rowname, y=mark)) +
  geom_bar(stat="identity", fill="#69b3a2", width=0.6) +
  coord_flip() +
  #theme_ipsum() +
  theme(
    panel.grid.minor.y = element_blank(),
    panel.grid.major.y = element_blank()
  ) +
  ylim(0,20) +
  ylab("mark") +
  xlab("") +
  facet_wrap(~name, ncol=4)



来源:https://stackoverflow.com/questions/64289738/facet-wrap-of-a-lollipop-plot

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