[英]Create a plot, flipping axes while keeping the same scale
我正在繪制一些圖表,向高中生介紹數學函數的概念。 現在,我想通過繪制水平拋物線為他們提供一個不是函數的示例:
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)
輸出以下圖像:
這與我想要的非常接近,但是我希望兩個軸的刻度都可以匹配,以使學生保持簡單。 為此,我嘗試使用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)
我的問題是: 有沒有簡單的方法可以將coord_flip功能包含到coord_equal中?
例如,我知道可以通過使用參數ylim和xlim獲得coord_cartesian功能。
根據您的用例,您似乎並不需要翻轉坐標:您可以顛倒x和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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.