【问题标题】:Overlapping many plots with ggplot2 in R在 R 中用 ggplot2 重叠许多图
【发布时间】:2022-01-18 14:31:06
【问题描述】:

我有以下数据框:

df1<-data.frame(id_1=c(1,2,3,4,5),
                value1=c(0,0.2,0.5,0.8,0),
                value2=c(0.1,0.3,0.5,0.7,0.8),
                value3=c(0.5,0.6,0.3,0.2,0.1))

df2<-data.frame(id_2=c(1,2,3,4,5),
                value1=c(0,0.2,0.5,0.8,0),
                value2=c(0.1,0.1,0.5,0.6,0.7),
                value3=c(0.4,0.4,0.8,0.9,0.2))

我想制作以下情节:

ggplot(data.frame(x=df1$value1, y=df2$value1), aes(x=x, y=y)) + 
       geom_point() + 
       geom_point(data.frame(x=df1$value2, y=df2$value2), aes(x=x, y=y)) + 
       geom_point(data.frame(x=df1$value3, y=df2$value3), aes(x=x, y=y))

如何在不必为每个 value 列复制粘贴 geom_point() 的情况下制作该图?之后,如何找到最终重叠图中变量的相关系数?

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 喜欢this?还是this 或this?绑定数据框后,只需使用cor 获取系数

标签: r ggplot2


【解决方案1】:

您需要将数据合并到一个数据框中。这是一种方法:

## make column names the same
## and add columns indicating the data frame source
df1$var = "x"
df2$var = "y"
names(df1)[1] = "id"
names(df2)[1] = "id"

## put the data together
df = rbind(df1, df2)

## reshaped the data
library(tidyr) 
df = pivot_longer(df, starts_with("value"))
df = pivot_wider(df, names_from = "var", values_from = "value")
df
# # A tibble: 15 × 4
#       id name       x     y
#    <dbl> <chr>  <dbl> <dbl>
#  1     1 value1   0     0  
#  2     1 value2   0.1   0.1
#  3     1 value3   0.5   0.4
#  4     2 value1   0.2   0.2
#  5     2 value2   0.3   0.1
#  6     2 value3   0.6   0.4
#  7     3 value1   0.5   0.5
#  8     3 value2   0.5   0.5
#  9     3 value3   0.3   0.8
# 10     4 value1   0.8   0.8
# 11     4 value2   0.7   0.6
# 12     4 value3   0.2   0.9
# 13     5 value1   0     0  
# 14     5 value2   0.8   0.7
# 15     5 value3   0.1   0.2

一旦您的数据格式整齐,绘图就很简单。您可以使用shape 或color 美学进一步自定义您的绘图以识别数据源。

ggplot(df, aes(x = x, y = y)) +
  geom_point()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 2017-09-12
    • 2014-12-08
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多