ggplot自定义X轴顺序、绘图优化及图表选型技术咨询
问题背景
我有如下数据集:
data <- c('real','real','real','real','real','pred','pred','pred','pred','pred','real','real','real','real','pred','pred','pred','pred') threshold <- c('>=1','>=2','>=3','>=4','>=101','>=1','>=2','>=3','>=4','>=101','>=1','>=2','>=3','>=4','>=1','>=2','>=3','>=4') accuracy <- c(63.4,64.4,65.1,64.3,65.4,62.1,63.6,64.1,65.4,64.8,62.2,63.3,64.4,65.6,63.1,63.8,64.6,65.1) types<-c('morning','morning','morning','morning','morning','morning','morning','morning','morning','morning','evening','evening','evening','evening','evening','evening','evening','evening') df <- data.frame(data,threshold,accuracy,types)
我想用facet_wrap分别针对morning和evening绘制data列的分组条形图,代码如下:
ggplot(df, aes(x = threshold, y = accuracy)) + geom_bar(aes(fill = data), stat = "identity", color = "white",position = position_dodge(0.9))+ facet_wrap(~types) + fill_palette("jco")
但当前图表存在一些问题:
threshold的顺序混乱,需要morning的顺序为'>=1','>=2','>=3','>=4','>=101',evening的顺序为'>=1','>=2','>=3','>=4'evening类别不应出现'>=101',如何移除?- 能否设置图表背景为白色但保留网格线?
- 作为可视化新手,有没有比当前分组条形图更合适的图表类型?
解决方案
1. 强制指定X轴顺序
要实现分面板的自定义X轴顺序,先清洗数据,再针对不同types给threshold设置对应因子水平即可:
# 先过滤数据(同时解决问题2) df_clean <- df %>% filter(!(types == "evening" & threshold == ">=101")) # 按types设置threshold的自定义顺序 df_clean <- df_clean %>% group_by(types) %>% mutate(threshold = factor(threshold, levels = ifelse(types == "morning", c(">=1", ">=2", ">=3", ">=4", ">=101"), c(">=1", ">=2", ">=3", ">=4")))) %>% ungroup()
后续绘图时X轴就会严格按指定顺序显示。
2. 移除evening的>=101
上面代码中的filter(!(types == "evening" & threshold == ">=101"))已经直接从数据中删除了evening分组下threshold为>=101的记录,绘图时自然不会显示该类别。
3. 设置白色背景并保留网格线
使用ggplot2的theme_bw()主题即可实现,它默认是白色背景+灰色网格线,还可以微调网格线样式:
ggplot(df_clean, aes(x = threshold, y = accuracy)) + geom_bar(aes(fill = data), stat = "identity", color = "white", position = position_dodge(0.9)) + facet_wrap(~types) + fill_palette("jco") + theme_bw() + # 可选:微调网格线颜色和隐藏次要网格线 theme(panel.grid.major = element_line(color = "#e0e0e0"), panel.grid.minor = element_blank())
4. 更合适的图表类型推荐
对于当前的精度对比场景,推荐以下两种更直观的图表:
- 分组折线图:更适合展示
accuracy随threshold的变化趋势,能快速对比real和pred的精度差异,比条形图节省空间:ggplot(df_clean, aes(x = threshold, y = accuracy, color = data, group = data)) + geom_line(size = 1) + geom_point(size = 2) + facet_wrap(~types) + theme_bw() - 误差线柱状图:如果后续有重复实验的精度数据,可以添加误差线展示波动;但当前只有单值数据,分组条形图也能用,不过折线图的趋势表现力更强。
如果核心是看不同阈值下的精度变化,分组折线图是最优选择,新手也容易上手。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

