【问题标题】:Facet wrap of a lollipop plot棒棒糖情节的分面包装
【发布时间】:2021-01-25 02:34:32
【问题描述】:

我正在尝试使用 facet wrap 制作多个棒棒糖图,如第三个代码块/示例和下面this page 上的图片。

但是,我无法让代码示例正常工作。你能帮我看看哪里写错了吗(如果有的话)?

数据:

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")

当我运行代码来绘制它时:

# 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)

我收到以下错误:

顺序错误(V1):找不到对象“V1”

链接页面上的前两个代码块依赖于两个列标题,所以我认为第一个向量自动命名为 V1。但我不清楚如何修复此示例代码,因为列已经命名。我希望这个问题很清楚。

【问题讨论】:

    标签: r ggplot2 dplyr tidyverse


    【解决方案1】:

    列名保持不变,因此您没有V1V2 列。您也可以将gather 替换为pivot_longer。试试看:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-15
      • 2015-08-12
      • 2020-04-16
      • 1970-01-01
      • 2016-05-02
      • 2015-05-22
      • 2015-02-21
      • 1970-01-01
      相关资源
      最近更新 更多