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

ggplot2中旋转轴标题与调整y轴刻度间距的技术咨询

问题解答

1. 将y轴标题改为水平显示

你之前的代码里,theme(axis.title.y = element_text(angle = 0))被后面的theme_classic()覆盖了——ggplot的theme设置遵循后执行覆盖先执行的规则。解决方法很简单,把自定义的theme设置放在theme_classic()之后即可,同时可以加上vjust=0.5让标题垂直居中对齐:

ggplot(Project, aes(x = Year)) +
  geom_line(aes(y = SHL, color = "Sheltered Hispanic or Latino")) +
  geom_line(aes(y = UHL, color = "Unsheltered Hispanic or Latino")) +
  scale_color_manual(values=c("blue","red"))+
  labs(title = "Homelessness by Ethnicity",
       y = "Number of People", color = "Status",
       caption = "Source: 2022 AHAR: Part 1 - PIT Estimates of Homelessness in the U.S. \n Hispanic or Latino data only available since 2015.") +
  scale_x_continuous(breaks = seq(2015,2022, 2)) +
  scale_y_continuous(breaks = seq(0, 40, 5)) + 
  theme_classic() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5))

2. 调整y轴刻度间距使其均匀

从你的描述来看,0到10的刻度间距偏小,是因为ggplot自动根据数据扩展了y轴范围(比如数据中存在大于40的数值),导致刻度的实际像素间距不一致。解决方法是强制锁定y轴范围,让它严格从0到40,这样每5个单位的刻度间距就会完全均匀:

修改scale_y_continuous,添加limits=c(0,40)参数:

scale_y_continuous(breaks = seq(0, 40, 5), limits = c(0, 40))

完整修正代码

ggplot(Project, aes(x = Year)) +
  geom_line(aes(y = SHL, color = "Sheltered Hispanic or Latino")) +
  geom_line(aes(y = UHL, color = "Unsheltered Hispanic or Latino")) +
  scale_color_manual(values=c("blue","red"))+
  labs(title = "Homelessness by Ethnicity",
       y = "Number of People", color = "Status",
       caption = "Source: 2022 AHAR: Part 1 - PIT Estimates of Homelessness in the U.S. \n Hispanic or Latino data only available since 2015.") +
  scale_x_continuous(breaks = seq(2015,2022, 2)) +
  scale_y_continuous(breaks = seq(0, 40, 5), limits = c(0, 40)) + 
  theme_classic() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5))

内容的提问来源于stack exchange,提问作者user12137078

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:40:07