ggplot2整数类x轴标签间隔显示,转字符正常,是否与sjPlot有关?
问题原因
该问题是ggplot2本身的内置机制导致的,和sjPlot的主题配置没有关联:
- 当x轴映射的
Year列为整数/数值类型时,ggplot会将其识别为连续型变量,会自动根据x轴范围、绘图区域大小计算默认的刻度间隔,你当前数据中年份范围为2012-2020,ggplot默认取间隔为2展示标签,因此出现隔一个年份显示一次的情况。 - 当你将
Year转为字符/因子类型时,ggplot会将其识别为离散型分类变量,默认会展示所有类别的对应标签,因此显示正常。
解决方案
你可以根据需求选择以下任意一种方案解决,无需修改原数据类型也可实现全标签展示:
- 指定连续x轴的刻度值
在绘图代码中新增scale_x_continuous()配置,明确指定要展示的刻度:
ggplot(df)+ geom_bar(aes(x=Year, y=`Number of Counties`, fill=Type), stat="identity") + scale_fill_manual(values = getPalette(colourCount)) + # 新增该行,指定x轴刻度为所有存在的年份 scale_x_continuous(breaks = unique(df$Year)) + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1), legend.key.height=unit(.75, "cm"))+ ggtitle('VT Disaster Designations: 2012-2020\nNote some counties have more than one\ndisaster type per year')
- 映射时直接转为离散因子
不需要修改原数据框,在aes映射时直接将Year转为因子类型即可:
ggplot(df)+ # 仅修改x映射部分 geom_bar(aes(x=factor(Year), y=`Number of Counties`, fill=Type), stat="identity") + scale_fill_manual(values = getPalette(colourCount)) + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1), legend.key.height=unit(.75, "cm"))+ # 可修改x轴名称为原来的Year labs(x = "Year") + ggtitle('VT Disaster Designations: 2012-2020\nNote some counties have more than one\ndisaster type per year')
- 设置固定刻度间隔
如果需要保留x轴的连续属性,可以借助scales包的工具设置固定间隔为1年:
# 需先加载scales包 library(scales) ggplot(df)+ geom_bar(aes(x=Year, y=`Number of Counties`, fill=Type), stat="identity") + scale_fill_manual(values = getPalette(colourCount)) + # 设置刻度间隔为1 scale_x_continuous(breaks = breaks_width(1)) + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1), legend.key.height=unit(.75, "cm"))+ ggtitle('VT Disaster Designations: 2012-2020\nNote some counties have more than one\ndisaster type per year')
你可以通过关闭sjPlot主题、使用ggplot默认主题绘图验证:整数类型的Year列同样会出现间隔显示的问题,进一步确认该现象和sjPlot的主题配置无关。
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

