用ggplot绘制2个散点图

时间:2020-06-27 20:47:51

标签: r dataframe ggplot2 plot plotly

我想用ggplot绘制2个散点图,但我对此不太熟悉。我一直在尝试遵循其他示例,但是对该程序包的分层方法使我感到困惑。

bothfrontier_data中,我希望第一列是相对于第三列的x变量,第二列是相对于第四列的x变量。另外,如何向该图添加自定义轴标题并添加自定义轴范围? 谢谢

############# GGPLOT TO SHOW BOTH PLOTS SUPERIMPOSED ###################################
bothfrontier_data <- data.frame(std_portfolios_Qts, std_portfolios_Qsi,
                                All_Portfolio_Returns_Qts, All_Portfolio_Returns_Qsi)
head(bothfrontier_data)
#   std_portfolios_Qts std_portfolios_Qsi All_Portfolio_Returns_Qts All_Portfolio_Returns_Qsi
#1          0.8273063          0.8194767                 0.3421454                 0.3357710
#2          0.8272188          0.8196555                 0.3421551                 0.3357853
#3          0.8273064          0.8192980                 0.3421648                 0.3357996
#4          0.8271314          0.8194769                 0.3421744                 0.3358139
#5          0.8272191          0.8194770                 0.3421840                 0.3358281
#6          0.8272193          0.8194772                 0.3421935                 0.3358423

dim(bothfrontier_data)
#[1] 501   4

BothFrontiers <- ggplot(bothfrontier_data, aes(x=std_portfolios_Qts)) +
  geom_point(aes(y=All_Portfolio_Returns_Qts), color = "blue") +
  geom_point(aes(y=All_Portfolio_Returns_Qsi), color = "red")
plot(BothFrontiers)

1 个答案:

答案 0 :(得分:1)

您可以尝试:

library(ggplot2)
library(patchwork)
#Plot 1
g1 <- ggplot(bothfrontier_data,aes(x=std_portfolios_Qts,y=All_Portfolio_Returns_Qts))+geom_point(color='blue')+
  ggtitle('Plot 1')
#Plot 2
g2 <- ggplot(bothfrontier_data,aes(x=std_portfolios_Qsi,y=All_Portfolio_Returns_Qsi))+geom_point(color='red')+
  ggtitle('Plot 2')
#Final plot
g1/g2

enter image description here

您可以使用scale_x_continuous()scale_y_continuous()修改轴。可以使用xlab()ylab()添加标签。希望对您有所帮助。