You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot点图中手动设置y轴范围为-3至3?

解决ggplot点图y轴范围无法扩展到-3的问题

你的问题核心在于nota列是因子类型,当前因子水平里没有"-3",所以ggplot默认只会显示数据中存在的刻度值。直接用ylim=c(-3,3)(适用于连续型变量)或错误调用scale_y_discrete都无法解决,正确做法是先扩展因子水平,再设置y轴刻度:

步骤1:扩展nota的因子水平

把"-3"添加到nota的因子水平中,同时保持刻度的顺序正确:

df.dot$nota <- factor(df.dot$nota, levels = c("-3", "-2", "-1", "0", "1", "2", "3"))

步骤2:修改ggplot代码设置y轴刻度

在原有代码中加入scale_y_discrete(limits = c("-3", "-2", "-1", "0", "1", "2", "3")),完整代码如下:

# 先扩展因子水平
df.dot$nota <- factor(df.dot$nota, levels = c("-3", "-2", "-1", "0", "1", "2", "3"))

# 绘制图形
graf.dot <- ggplot(df.dot,aes(x = data, y = nota, group = data, fill = colour, colour = colour)) + 
  facet_wrap(~taxa) + 
  geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 2) + 
  scale_fill_manual(values = c('Negativo' = 'red','Neutro' = 'gray','Positivo'='green','Ref' = 'black')) + 
  scale_colour_manual(values = c('Negativo' = 'red','Neutro' = 'gray','Positivo'='green','Ref' = 'black')) + 
  scale_y_discrete(limits = c("-3", "-2", "-1", "0", "1", "2", "3")) + # 设置y轴刻度范围
  ggtitle("Notas \n") +  
  xlab("") + 
  ylab("") + 
  theme(plot.title = element_text(size = 20, hjust = 0.5), 
        axis.text.y = element_text(size = 18), 
        axis.text.x = element_text(size = 18),
        legend.key = element_blank(), 
        legend.title = element_blank(), 
        legend.text = element_text(size = 18), 
        legend.position = "bottom", 
        strip.text = element_text(size = 18))

# 输出图形
print(graf.dot)

修改后,y轴会完整显示-3到3的范围,即使数据中没有-3对应的点。

内容的提问来源于stack exchange,提问作者Osvaldo Assunção

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:05:17