首页 > 解决方案 > 限制 ggplot2 绘图的 X 和 Y 轴

问题描述

我正在使用辅助轴(按比例缩放)来显示绘图的公制/英制单位。我希望将绘图区域限制为 (1500,0) 和 (5000,350) - 两者都设置在主坐标中。我尝试了以下方法:

这些都没有改变我的情节。我想摆脱红线突出显示的区域(裁剪图): 在此处输入图像描述

这是一个最小的工作示例mtcars,尽管将 x 上限指定为 10,但该图显示了超出该范围的数据。我希望情节裁剪到指定的限制。有没有办法做到这一点?

ggplot(as.data.table(mtcars)) + 
  geom_line(aes(x = wt, y = mpg, color= factor(cyl))) + 
  ylab('Fuel Economy (mpg)') + 
  scale_y_continuous(sec.axis = sec_axis(~.*1.6/3.7854, name = 'Fuel Economy (kmpl)')) + 
  xlab('Weight (lbs)') + 
  scale_x_continuous(sec.axis = sec_axis(~./2.20462, name = 'Weight (kg)'), position = 'bottom') + 
  theme_light() + 
  theme(
    legend.position = c(0.15, 0.75),
    legend.title = element_blank(),
    axis.title.y.right = element_text(
      angle = 90,
      margin = margin(r = 0.8 * 11,
                      l = 0.8 * 11 / 2)
    )
  ) + 
  coord_cartesian(xlim = c(0, 5), ylim = c(10, 35))

在此处输入图像描述

标签: rggplot2

解决方案


在 scale_x_continuous 和 scale_y_continuous 中添加限制和扩展参数。您也可以添加休息时间。

ggplot(as.data.table(mtcars)) + 
  geom_line(aes(x = wt, y = mpg, color= factor(cyl))) + 
  ylab('Fuel Economy (mpg)') + 
  scale_y_continuous(limits = c(10, 35), expand = c(0, 0), 
                     sec.axis = sec_axis(~.*1.6/3.7854, name = 'Fuel Economy (kmpl)')
                     ) + 
  xlab('Weight (lbs)') + 
  scale_x_continuous(limits = c(0, 5), expand = c(0, 0), 
                     sec.axis = sec_axis(~./2.20462, name = 'Weight (kg)'), position = 'bottom') + 
  theme_light() + 
  theme(
    legend.position = c(0.15, 0.75),
    legend.title = element_blank(),
    axis.title.y.right = element_text(
      angle = 90,
      margin = margin(r = 0.8 * 11,
                      l = 0.8 * 11 / 2)
    )
  ) 

在此处输入图像描述


推荐阅读