如何调整ggplot2离散Y轴刻度范围与间隔(0-100,步长10)
解决ggplot2设置Y轴刻度范围与间隔报错的问题
报错原因
你误将Y轴变量ExpeditedDrugsProportion转换成了因子类型,ggplot2会把因子变量识别为离散轴,而ylim、scale_y_continuous()是用于配置连续数值轴的函数,两者不匹配导致报错。
修正方案
- 删除
df$ExpeditedDrugsProportion <- as.factor(df$ExpeditedDrugsProportion)这行代码,保留变量的数值类型 - 使用
scale_y_continuous()设置Y轴范围为0-100,刻度间隔为10,通过limits参数定义范围,breaks参数生成等间隔刻度点
完整修正代码
library(ggplot2) library(dplyr) library(readr) library(janitor) library(RColorBrewer) library(forcats) # 创建数据框 df <- data.frame(Year = c("2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022"), ExpeditedDrugsProportion = c(51, 48, 66, 60, 73, 61, 73, 60, 68, 74, 65) ) # 创建图表并配置Y轴刻度 ExpeditedApprovals_graph <- ggplot(df, aes(x = Year, y = ExpeditedDrugsProportion)) + geom_point() + labs(title = "", x = "Year", y = "Proportion of newly approved drugs expedited (%)") + theme_classic(base_size = 20) + scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, 10)) ExpeditedApprovals_graph
补充说明
如果因特殊需求必须保留因子类型(不推荐,比例属于连续数值),只能使用scale_y_discrete()配置,但无法实现0-100的连续刻度效果,因此优先推荐保持变量为数值类型的方案。
内容的提问来源于stack exchange,提问作者Bob_123
相关产品推荐
相关产品推荐

