繁体   English   中英

使用ggplot2绘制两个变量 - 相同的x轴

[英]Plotting two variables using ggplot2 - same x axis

我有两个具有相同x轴的图形 - 两个图形中x的范围均为0-5。 我想将它们两者合并到一个图表中,我没有找到前面的例子。 这是我得到的:

c <- ggplot(survey, aes(often_post,often_privacy)) + stat_smooth(method="loess")
c <- ggplot(survey, aes(frequent_read,often_privacy)) + stat_smooth(method="loess")

我该如何组合它们? y轴“通常是隐私的”,并且在每个图中,x轴“经常发布”或“频繁读取”。 我认为我可以轻松地(不知何故)将它们组合起来,因为它们的范围都是0-5。

非常感谢!

Ben解决方案的示例代码。

#Sample data
survey <- data.frame(
  often_post = runif(10, 0, 5), 
  frequent_read = 5 * rbeta(10, 1, 1), 
  often_privacy = sample(10, replace = TRUE)
)
#Reshape the data frame
survey2 <- melt(survey, measure.vars = c("often_post", "frequent_read"))
#Plot using colour as an aesthetic to distinguish lines
(p <- ggplot(survey2, aes(value, often_privacy, colour = variable)) + 
  geom_point() +
  geom_smooth()
)

您可以使用+在同一ggplot对象上组合其他绘图。 例如,要为两对列绘制点和平滑线:

ggplot(survey, aes(often_post,often_privacy)) + 
geom_point() +
geom_smooth() + 
geom_point(aes(frequent_read,often_privacy)) + 
geom_smooth(aes(frequent_read,often_privacy))

试试这个:

df <- data.frame(x=x_var, y=y1_var, type='y1') 
df <- rbind(df, data.frame(x=x_var, y=y2_var, type='y2'))
ggplot(df, aes(x, y, group=type, col=type)) + geom_line()

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM