使用ggplot绘制三大洲多表型年度趋势图为空问题求助
解决ggplot绘制AMR趋势图为空的问题
问题背景
读取amr_paraB_trends.csv数据,表内包含16列:
- Continents:取值为America、Asia、Europe
- Years:1965-2021年间的年份(如1965、1976等)
- 14种表型列:Streptomycin、Kanamycin等
执行以下代码将数据转换为长格式:
amr$Years <- format(amr$Years, format = "%Y") library(ggplot2) library(tidyr) df_long <- pivot_longer(amr, cols = c(Streptomycin, Spectinomycin, Kanamycin, Ampicillin, Trimethoprim, Chloramphenicol, Ciprofloxacin_IR, Sulfisoxazole, Tetracycline, Nalidixic_acid, Colistin, Cefoxitin, Ceftriaxone, Lincomycin), values_to = "Isolates", names_to = "Phenotypes")
尝试绘制各表型随年份变化的趋势图(按大洲区分线型),但执行下方代码后图表为空:
ggplot(df_long, aes(x = Years, y = Isolates, color = Phenotypes, linetype = Continents)) + geom_line(size = 0.7) + ggtitle("Trend of amr over years") + xlab("Year") + ylab("No of isolates) + #x_continuous(breaks = seq(1975, 2022, by = 1)) + theme_minimal()
问题排查与修复方案
1. 修正Years的数据类型
用format()把Years转成了字符型,ggplot绘制折线图时,字符型x轴无法识别为连续的时间序列,自然画不出折线。需要把Years转回数值型:
替换原代码中的amr$Years <- format(amr$Years, format = "%Y")为:
# 如果原Years是日期类型,提取年份并转数值 amr$Years <- as.numeric(format(amr$Years, format = "%Y")) # 如果原Years本身就是数值(比如直接存的1965、1976数字),直接删掉format那行就行
2. 修复ylab的语法错误
ylab("No of isolates)里少了一个闭合双引号,这会触发语法错误,导致图表无法正常渲染。修正为:
ylab("No of isolates")
3. 正确设置x轴刻度(可选)
注释掉的x_continuous是错误的函数名,正确写法是scale_x_continuous。当Years转为数值型后,可以启用这行并调整刻度间隔(避免刻度太密集):
scale_x_continuous(breaks = seq(1975, 2021, by = 5))
4. 过滤缺失值(可选)
如果Isolates列存在大量NA,也会导致折线断裂或不显示。可以用drop_na()过滤掉缺失值:
df_long <- df_long %>% drop_na(Isolates)
最终完整修正代码
# 加载所需包 library(ggplot2) library(tidyr) library(dplyr) # 读取数据(假设已完成) # amr <- read.csv("amr_paraB_trends.csv") # 修正Years数据类型 amr$Years <- as.numeric(format(amr$Years, format = "%Y")) # 转换长格式并过滤缺失值 df_long <- pivot_longer(amr, cols = c(Streptomycin, Spectinomycin, Kanamycin, Ampicillin, Trimethoprim, Chloramphenicol, Ciprofloxacin_IR, Sulfisoxazole, Tetracycline, Nalidixic_acid, Colistin, Cefoxitin, Ceftriaxone, Lincomycin), values_to = "Isolates", names_to = "Phenotypes") %>% drop_na(Isolates) # 绘制趋势图 ggplot(df_long, aes(x = Years, y = Isolates, color = Phenotypes, linetype = Continents)) + geom_line(size = 0.7) + ggtitle("Trend of AMR over years") + xlab("Year") + ylab("No of isolates") + scale_x_continuous(breaks = seq(1975, 2021, by = 5)) + theme_minimal()
内容的提问来源于stack exchange,提问作者Safina A.R
相关产品推荐
相关产品推荐

