如何在R中绘制分类数据?ggplot分面条形图代码故障排查
解决R中分类数据条形图分面问题
先确认数据转换的正确性,再调整绘图细节,以下是完整可行的解决方案:
1. 正确转换宽格式数据为长格式
首先确保用pivot_longer时准确选中所有浓度列(0.25、0.5、1等),代码示例如下:
library(tidyverse) # 读入原始数据(这里用你的示例数据) df <- tibble( Antimicrobial = c("Amox/Clav", "Ampicillin", "Cefquinome", "Doxycycline", "Enrofloxacin", "Erythromycin", "Gentamicin", "Marbofloxacin", "Penicillin G"), `0.25` = c(95,48,0,554,21,106,0,0,10), `0.5` = c(393,100,0,2,125,110,1,25,6), `1` = c(223,528,24,1,355,236,13,71,27), `2` = c(3,35,28,5,52,176,90,406,376), `4` = c(0,3,245,35,162,87,132,213,259), `8` = c(1,1,418,118,0,0,479,0,37), `16` = c(0,0,0,0,0,0,0,0,0) ) # 转换为长格式 graphlong <- df %>% pivot_longer(cols = -Antimicrobial, # 排除抗菌药物列,转换其余所有列 names_to = "Concentration", # 将原列名转为"浓度"变量 values_to = "Count") # 将对应数值转为"计数"变量
2. 修正绘图代码
你的原代码核心问题是浓度变量的顺序是字符排序(比如1会排在16前面、0.5排在0.25后面),需要调整为逻辑顺序;同时可以优化分面布局提升可读性:
# 手动指定浓度的逻辑顺序,避免字符排序混乱 graphlong$Concentration <- factor(graphlong$Concentration, levels = c("0.25", "0.5", "1", "2", "4", "8", "16")) # 绘制分面条形图 graph_01 <- ggplot(data = graphlong, aes(x = Concentration, y = Count, fill = Concentration)) + geom_col(width = 0.7) + # 调整条形宽度,避免过于拥挤 facet_wrap(~Antimicrobial, ncol = 3) + # 按抗菌药物分面,每行显示3个 scale_fill_viridis_d() + # 选用区分度更高的配色(可选) labs(x = "浓度", y = "计数", title = "不同抗菌药物的浓度分布") + theme_bw() + # 使用简洁的白底主题 theme( axis.text.x = element_text(angle = 45, hjust = 1), # 旋转x轴标签,避免重叠 legend.position = "bottom" # 将图例移至底部,节省纵向空间 ) print(graph_01)
排查要点
如果运行后仍无预期效果,先检查graphlong的数据结构:
- 确认每一行是
Antimicrobial+Concentration+Count的格式 - 检查是否有缺失值或异常数值
内容的提问来源于stack exchange,提问作者Danny_0101
相关产品推荐
相关产品推荐

