r - 限制 ggplot2 绘图的 X 和 Y 轴
问题描述
我正在使用辅助轴(按比例缩放)来显示绘图的公制/英制单位。我希望将绘图区域限制为 (1500,0) 和 (5000,350) - 两者都设置在主坐标中。我尝试了以下方法:
xlim(c(1500,5000)) + ylim(c(0,350))
lims
具有与上述相同的论点coord_cartesian(xlim = c(1500, 5000), ylim = c(0, 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))
解决方案
在 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)
)
)
推荐阅读
- arrays - 保存 Fortran 静态数组以供以后运行
- oracle - 如何在 oracle 中确认 IMPDP 是否成功
- java - 如何在Java中创建具有可变对象名称的对象
- javascript - Node.js pug 模板中元素的显示值不会改变?另外,jQuery 不起作用?
- node.js - 请求正文长度中的字符串在 Express&&bodyparser 中始终受到限制
- javascript - Knockout JS textInput 绑定
- javascript - VSCode: [js] 这个构造函数可能会被转换为类声明
- react-native - 世博会相机 takePictureAsync ImageManipulator
- jquery - 使用 jquery 选择源“srcset”
- eloquent - 使用 Laravel 5.5 在 sql 更新请求上重复“deleted_at”