簡體   English   中英

如何 plot R 中的特定行和列

[英]How to plot specific rows and columns in R

我的數據框包含從 2019 年 1 月到 2020 年 10 月在英格蘭 9 個不同地區報告的 5 種犯罪類型(加上它們各自的發生次數)的列表。

我想 plot 一個圖表,其中犯罪發生率作為 Y 軸,日期作為每個區域的 X 軸,而不是面圖。

要做到這一點,我必須選擇我想要的區域 plot; 我試過了

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

您可以為每個區域創建一行 plot,如下所示:

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

Output:

在此處輸入圖像描述

更新:下一個代碼將為每個區域創建一個列表:

#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即可顯示所有繪圖。

一些 output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM