[英]Two plots in one plot with ggplot
I need to create "two plots" in "one plot" with ggplot.我需要用ggplot在“一个图”中创建“两个图”。 I managed to do it with base R as follows:
我设法用基础 R 做到了,如下所示:
x=rnorm(10)
y=rnorm(10)*20+100
plot(1:10,rev(sort(x)),cex=2,col='red',ylim=c(0,2.2))
segments(x0=1:10, x1=1:10, y0=1.8,y1=1.8+y/max(y)*.2,lwd=3,col='dodgerblue')
However, I am struggling with ggplot, how can it be done?但是,我在 ggplot 上苦苦挣扎,怎么办?
Here's one possible translation of that code.这是该代码的一种可能翻译。
ggplot(data.frame(idx=seq_along(x), x,y)) +
geom_point(aes(idx, rev(sort(x))), col="red") +
geom_segment(aes(x=idx, xend=idx, y=1.8, yend=1.8+y/max(y)*.2), color="dodgerblue")
In general with ggplot2, you can add multiple views of data to a plot by adding additional layers (geoms)一般来说,使用 ggplot2,您可以通过添加附加层(geoms)将多个数据视图添加到绘图中
My solution is similar to @MrFlick.我的解决方案类似于@MrFlick。
I would always recommend having a plot data frame and referring to the variables from there as you can more easily relate variables to plot aesthetics.我总是建议使用绘图数据框并从那里引用变量,因为您可以更轻松地将变量与绘图美学相关联。
library(tidyverse)
plot_df <- data.frame(x, y) %>%
arrange(-x) %>%
mutate(id = 1:10)
ggplot(plot_df) +
geom_point(aes(id, x), color = "red", pch = 1, size = 5) +
geom_segment(aes(x = id, xend = id, y = 1.8, yend = 1.8+y/max(y)*.2),
lwd = 2, color = 'dodgerblue') +
scale_y_continuous(limits = c(0,2.2)) +
theme_light()
Ultimately, the goal of ggplot is to add aesthetics (in this case, the points and the segments) to form the final plot.最终,ggplot 的目标是添加美感(在本例中为点和线段)以形成最终图。
If you'd like to learn more, check out the ggplot cheat sheet and read more on the ideas behind ggplot: https://ggplot2.tidyverse.org/如果您想了解更多信息,请查看 ggplot 备忘单并阅读更多关于 ggplot 背后的想法: https ://ggplot2.tidyverse.org/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.