【问题标题】:Breaking up a large ggplot by category; subset shows no errors but plots no data按类别分解一个大的ggplot;子集没有显示错误,但没有绘制数据
【发布时间】:2022-02-07 15:02:57
【问题描述】:

我有一个非常大的数据集,来自以下格式的电子表格:

df = data.frame(name = c('Ger1', 'Ger2', 'Ger3', 'Ger4', 'Ger5', 'Ger6'),
                issued = c(UKS, USD, UKS, UKS, USD, USD),
                mat = c(2024-01-31, 2023-01-31, 2026-10-22, 2022-07-22, 2029-01-31, 2025-06-07)
                volume = c(0.476, 0.922, 0.580, 1.259, 0.932, 0.417)

目前,我使用以下代码将所有数据绘制在一个非常长的 ggplot 上:

chart1<-ggplot(df)+geom_bar(stat="ID",aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),panel.background = element_rect(fill='white',color='black'),legend.position='right')+
    labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")

虽然这已经奏效了一段时间,但考虑到数据集已经增长到的规模,使用这种方式不再可行。因此,我想根据“已发布”列的内容绘制数据。

我首先想到了一个条件语句的类型:

if (df$issued == "UKS"){
chart1<-ggplot(df)+geom_bar(stat="ID",aes(x=volume,y=name),fill="#1170aa")+
      theme(title=element_text(size=12),panel.background = element_rect(fill='white',color='black'),legend.position='right')+
        labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
}

不幸的是,它不起作用(尽管仔细检查后,我的逻辑并没有经过深思熟虑)

然后我尝试使用子集()函数,希望只绘制满足我要求的数据:

chart1<-ggplot(subset(df, 'issued' == "UKS"))+geom_bar(stat="ID",aes(x=volume,y=name),fill="#1170aa")+
          theme(title=element_text(size=12),panel.background = element_rect(fill='white',color='black'),legend.position='right')+
            labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")

这个特定的代码没有显示任何错误,但是生成的图表没有任何数据。有人对我如何过滤和绘制这些数据有任何想法吗?

【问题讨论】:

    标签: r ggplot2 subset


    【解决方案1】:

    subset() 中的列名不需要引用 ""

    ggplot(subset(df, issued == "UKS")) +
      geom_bar(stat="identity", aes(x=volume,y=name),fill="#1170aa")+
      theme(title=element_text(size=12),
            panel.background = element_rect(fill='white',color='black'),
            legend.position='right')+
      labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
    

    或使用tidyverse 的绘图方式:

    library(tidyverse)
    
    df %>% filter(issued == "UKS") %>% 
      ggplot() +
      geom_bar(stat="identity", aes(x=volume,y=name),fill="#1170aa")+
      theme(title=element_text(size=12),
            panel.background = element_rect(fill='white',color='black'),
            legend.position='right')+
      labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
    

    【讨论】:

    • 非常感谢 benson23,太好了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 2020-06-08
    • 2016-06-29
    • 1970-01-01
    相关资源
    最近更新 更多