创建绘图,在保持相同比例的同时翻转轴

时间:2018-02-23 01:27:38

标签: r ggplot2

我正在绘制一些图表,向高中学生介绍数学函数的概念。现在,我想通过绘制水平抛物线给他们一个不是函数的例子:

x <- seq(from = -3, to = 3, by = 0.001)
y <- -x^2 + 5

grafico <- ggplot()+
  geom_hline(yintercept = 0)+
  geom_vline(xintercept = 0)+
  geom_line(mapping = aes(x = x, y = y),color="darkred",size=1)+
  theme_light()+
  xlab("")+
  ylab("")+
  scale_x_continuous(breaks = seq(from = -100, to = 100, by = 1))+
  scale_y_continuous(breaks = seq(from = -100, to = 100, by = 1))+
  coord_flip(ylim = c(-1.5,5.5), xlim = c(-3,3),expand = FALSE)

print(grafico)

输出以下图像:

enter image description here

这与我想要的非常接近,但我想要两个轴&#39;缩放比例,为学生保持简单。为此,我尝试使用coord_equal,但不幸的是,它似乎取消了coord_flip的效果:

    x <- seq(from = -3, to = 3, by = 0.001)
y <- -x^2 + 5

grafico <- ggplot()+
  geom_hline(yintercept = 0)+
  geom_vline(xintercept = 0)+
  geom_line(mapping = aes(x = x, y = y),color="darkred",size=1)+
  theme_light()+
  xlab("")+
  ylab("")+
  scale_x_continuous(breaks = seq(from = -100, to = 100, by = 1))+
  scale_y_continuous(breaks = seq(from = -100, to = 100, by = 1))+
  coord_flip(ylim = c(-1.5,5.5), xlim = c(-3,3),expand = FALSE)+
  coord_equal()

print(grafico)

enter image description here

我的问题是:是否有一种简单的方法可以将coord_flip功能包含在coord_equal中?

例如,我知道我可以获得coord_cartesian功能by using the parameters ylim and xlim

1 个答案:

答案 0 :(得分:2)

根据您的使用情况,看起来您似乎需要来翻转坐标:您可以反转x&amp;的输入顺序。 y,并使用geom_path()代替geom_line()来强制绘图遵循输入中的顺序。

ggplot帮助文件说明:

  

geom_path()按照它们的顺序连接观察结果   出现在数据中。 geom_line()按顺序连接它们   x轴上的变量。

ggplot() +
  geom_hline(yintercept = 0) +
  geom_vline(xintercept = 0) +
  geom_path(mapping = aes(x = y, y = x), color="darkred", size = 1) + # switch x & y here
  theme_light() +
  xlab("") +
  ylab("") +
  scale_x_continuous(breaks = seq(from = -100, to = 100, by = 1)) +
  scale_y_continuous(breaks = seq(from = -100, to = 100, by = 1)) +
  coord_equal(xlim = c(-1.5, 5.5), ylim = c(-3, 3), expand = FALSE) # switch x & y here

plot