如何在ggplot2中将y轴刻度的连字符替换为减号
解决ggplot2 y轴刻度连字符替换为减号的问题
方法1:用scales包动态生成带正确减号的标签
不用手动逐个写标签,借助scales的格式化函数自动生成带Unicode减号(U+2212)的刻度文本,更灵活且不易出错:
library(ggplot2) library(scales) plot <- ggplot(df_1, aes(x=t, y=RMS, color=Outcome, fill=Outcome, shape=Outcome)) + scale_y_continuous( limits = c(-0.02, 0.02), breaks = seq(-0.02, 0.02, by=0.01), labels = label_number(negative_sign = "−") )
方法2:修复手动标签的解析问题
如果坚持手动指定标签,开启parse=TRUE让ggplot2正确识别特殊字符,同时确保代码文件编码为UTF-8:
plot <- ggplot(df_1, aes(x=t, y=RMS, color=Outcome, fill=Outcome, shape=Outcome)) + scale_y_continuous( limits = c(-0.02, 0.02), breaks = seq(-0.02, 0.02, by=0.01), labels = c("−0.02", "−0.01", "0", "0.01", "0.02"), parse = TRUE )
方法3:检查字体兼容性
部分默认字体不支持Unicode减号,更换为支持的字体(如Arial、Roboto):
plot <- ggplot(df_1, aes(x=t, y=RMS, color=Outcome, fill=Outcome, shape=Outcome)) + scale_y_continuous( limits = c(-0.02, 0.02), breaks = seq(-0.02, 0.02, by=0.01), labels = label_number(negative_sign = "−") ) + theme(text = element_text(family = "Arial"))
Windows系统需先通过windowsFonts()注册对应字体再使用。
内容的提问来源于stack exchange,提问作者Newcomer
相关产品推荐
相关产品推荐

