在R中绘制多时间序列图:跨年份多数据可视化问题
解决跨年份多疾病死亡数据的可视化问题
我看了你尝试的代码,问题主要出在日期处理逻辑混乱和ggplot语法错误上——你重复覆盖了yStart变量,最后用字符串拼接的年份作为x轴,没法正确展示时间跨度。参考你想要的BBC风格图表,我们可以用geom_segment来绘制每个疾病的时间区间,配合对数刻度处理死亡数的巨大差异,这样就能直观对比不同疾病的流行时长和致死规模。
修正后的完整代码
library(lubridate) library(ggplot2) # 先清理数据:修正乱码的列名,整理数据结构 otherDiseaseData <- structure(list( ï..Disease = structure(c(11L, 2L, 12L, 6L, 3L, 1L, 9L, 7L, 13L, 4L, 5L, 8L, 10L), .Label = c("Asian Flu", "blackdeath", "Cholera", "Covid 19", "Ebola", "HIV", "Hong Kong Flu", "Mers", "Russian Flu", "Sars", "smallpox", "spanish flu", "Swine Flu" ), class = "factor"), Start = c(0L, 1347L, 1918L, 1981L, 1899L, 1957L, 1889L, 1968L, 2009L, 2019L, 2014L, 2012L, 2002L), End = c(1979L, 1351L, 1919L, 2020L, 1923L, 1958L, 1890L, 1970L, 2010L, 2020L, 2016L, 2020L, 2003L), Death = c(300000L, 225000000L, 50000L, 2360000L, 1500000L, 1100000L, 1000000L, 1000000L, 151700L, 101526L, 11300L, 866L, 774L) ), class = "data.frame", row.names = c(NA, -13L)) # 重命名乱码的疾病列 names(otherDiseaseData)[1] <- "Disease" # 绘制可视化图表 ggplot(otherDiseaseData, aes(y = Death)) + # 绘制每个疾病的时间跨度线段:x是起始年,xend是结束年,y和yend都是死亡数 geom_segment(aes(x = Start, xend = End, yend = Death, color = Disease), size = 2, lineend = "round") + # 添加疾病名称标注,放在线段中间位置 geom_text(aes(x = (Start + End)/2, label = Disease), vjust = -0.5, size = 3.5) + # 因为死亡数差距极大,用对数刻度让小数值也能清晰展示 scale_y_log10(labels = scales::comma) + # 设置x轴为年份刻度,调整范围覆盖所有数据 scale_x_continuous(limits = c(0, 2025), breaks = seq(0, 2000, 500)) + # 添加标题和轴标签 labs(title = "Deadly Disease Outbreaks: Time Span vs. Mortality", x = "Year", y = "Number of Deaths (Log Scale)", color = "Disease") + # 调整主题,让图表更清晰 theme_minimal() + theme(plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.title = element_text(size = 12), legend.position = "none") # 因为已经用文本标注,隐藏图例
关键修正点说明
- 数据清理:先把乱码的列名
ï..Disease重命名为Disease,避免后续代码出错 - 时间跨度可视化:用
geom_segment替代geom_point,直接绘制每个疾病从起始年到结束年的水平线段,完美对应你想要的时间周期展示效果 - 对数刻度适配:死亡数从774到2.25亿,差距超过3个数量级,用
scale_y_log10可以让所有疾病的死亡数都在图表上清晰呈现 - 直观文本标注:在每个线段的中间位置添加疾病名称,避免图例的混乱,让读者一眼就能对应疾病和数据
这样生成的图表就和你参考的BBC风格一致了,能清晰对比不同疾病的流行时长和致死规模。
内容的提问来源于stack exchange,提问作者Shelby Labuschagne
相关产品推荐
相关产品推荐

