【问题标题】:How to plot specific rows and columns in R如何在 R 中绘制特定的行和列
【发布时间】:2021-01-11 15:12:16
【问题描述】:

我的数据框包含从 2019 年 1 月到 2020 年 10 月在英格兰 9 个不同地区报告的 5 种犯罪类型(加上它们各自的发生次数)的列表。

我想为每个区域分别绘制以犯罪发生率为 Y 轴,以日期为 X 轴的图表,而不是多面图表。

为此,我必须挑选出我想要绘制的区域;我试过了

df$region == "Region_name"

但它没有成功。 任何建议将不胜感激!

这是我正在使用的数据框示例:

structure(list(
Region = c("Yorkshire and The Humber", "East of England", 
  "East Midlands", "North East", "South East", "South East", "South East", 
  "East Midlands", "East Midlands", "London", "North West", "South West", 
  "East of England", "East Midlands", "East Midlands", "South East", 
  "Yorkshire and The Humber", "East of England", "East of England", 
  "East of England"), 
Date = structure(c(18109, 18383, 17928, 18293, 
  18414, 18536, 18170, 17987, 18322, 18140, 18383, 18475, 18231, 
  18048, 18353, 18322, 18475, 18170, 18109, 17897), class = "Date"), 
Crime = c("Violence and sexual offences", "Robbery", "Violence and sexual offences", 
    "Robbery", "Burglary", "Violence and sexual offences", "Robbery", 
    "Burglary", "Violence and sexual offences", "Robbery", "Robbery", 
    "Burglary", "Robbery", "Theft", "Violence and sexual offences", 
    "Burglary", "Burglary", "Robbery", "Anti-social behaviour", 
    "Theft"), 
Crime_occurrencies = c(21001L, 177L, 6033L, 82L, 
    2635L, 24096L, 590L, 1536L, 7388L, 3205L, 163L, 981L, 232L, 
    5339L, 6367L, 3375L, 3238L, 257L, 10982L, 7906L)), 
class = "data.frame", row.names = c(NA, -20L))

【问题讨论】:

    标签: r ggplot2 linegraph


    【解决方案1】:

    您可以像这样为每个区域创建线图:

    library(ggplot2)
    #Code
    ggplot(df,aes(x=Date,y=Crime_occurrencies,color=Region))+
      geom_line()+
      geom_point()
    

    输出:

    更新:接下来的代码将为每个区域创建一个列表:

    #Unique regions
    uni <- unique(df$Region)
    #Plot func
    myplot <- function(x)
    {
      G <- ggplot(subset(df,Region==x),aes(x=Date,y=Crime_occurrencies,color=Crime))+
        geom_line()+
        geom_point()+
        ggtitle(x)
      G
    }
    #Apply
    List <- lapply(uni, myplot)
    

    只需在控制台上输入List,所有绘图都会出现。

    一些输出:

    【讨论】:

    • 谢谢!不过,我宁愿单独分析每个区域(即我需要一个让我选择一个区域进行绘图的代码),这样我就可以清楚地看到每种犯罪类型的发生如何随时间变化。我还将添加同一时间段内失业率变化的折线图,以研究与犯罪率的任何潜在关系,但我需要分别为每个区域执行此操作(避免分面图选项)
    • @Lactuca 您想要为每个区域绘制单独的图,但不要刻面,对吧?
    • 没错!而且我希望能够从同一个数据框中选择要绘制的内容,因此我不必为每个区域创建一个向量来单独绘制它。
    • @Lactuca 我可以添加一个代码来将所有地块存储在一个列表中,你同意吗?
    • @Lactuca 我已添加更新,请检查并告诉我是否有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多