使用ggplot2绘制多线时间序列图——网络攻击数据可视化问询
Got it, let's break down how to build that multi-line time series plot to visualize daily attack counts per server. Here's a step-by-step guide:
Step 1: Prep Your Data
First, your raw data has one row per attack—so we need to aggregate it to count how many attacks each server gets per day. We'll use dplyr for this (make sure you have it installed alongside ggplot2):
# Load required packages library(dplyr) library(ggplot2) # Aggregate attacks by host and date attack_summary <- china_atks %>% group_by(host, date) %>% summarize(daily_attacks = n(), .groups = "drop") # .groups = "drop" cleans up grouping after calculation
Pro Tip: Double-check that your date column is formatted as a Date type. If it's stored as text, convert it first with:
attack_summary <- attack_summary %>% mutate(date = as.Date(date))
Step 2: Build the Multi-Line Plot
Now we'll use ggplot2 to plot each server's daily attack trend as a separate line, colored by host:
ggplot(attack_summary, aes(x = date, y = daily_attacks, color = host)) + geom_line(linewidth = 1) + # Adjust line thickness for readability # Add labels and clean up the theme labs( title = "Daily Cyber Attacks by Server (7-Month Period)", x = "Date", y = "Number of Attacks", color = "Server Host" ) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.title = element_text(size = 12), legend.position = "right" # Move legend to bottom if you have many hosts: legend.position = "bottom" )
Optional: If You Have Too Many Servers
If you've got a ton of hosts, the legend will get messy. Instead, use faceting to give each server its own subplot:
ggplot(attack_summary, aes(x = date, y = daily_attacks)) + geom_line(linewidth = 1, color = "#2c3e50") + facet_wrap(~host, ncol = 2) + # Arrange subplots in 2 columns labs( title = "Daily Cyber Attacks by Server (7-Month Period)", x = "Date", y = "Number of Attacks" ) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.title = element_text(size = 12), strip.text = element_text(face = "bold") # Highlight host names in facets )
That should give you a clear, readable visualization of attack trends across your servers over the 7-month period!
内容的提问来源于stack exchange,提问作者Edward Gargan

