首页 > 解决方案 > 用手动图例绘制两个数据框

问题描述

我是 R 新手,我也想绘制两个带有图例的向量。Df 1 看起来像这样

> df1
      df1
1  0.03789634
2  0.24012665
3  0.33449574
4  0.28389631
5  0.27714124
6  0.27867639
7  0.35170168
8  0.32454339
9  0.20677891
10 0.34182049

Df 2 看起来像这样:

> df2
          df2
1      0.07975460
2      0.08639309
3      0.07079646
4      0.08163265
5      0.08139535
6      0.10379747
7      0.09550562
8      0.07961783
9      0.09225092
10     0.09090909

我可以执行以下操作并将它们绘制在一起,但我认为这太过分了,而且我发现添加图例非常困难。有没有更简单的方法可以将它们与关卡绑定在一起并以更优雅的方式使用 ggplot ?

df <- bind_cols(df1, df2)

p <- ggplot(df, aes(visits), fill=df) + scale_x_continuous(limits=c(1,10), breaks=1:10)
p + geom_line(aes(y=df1), colour="blue") + geom_line(aes(y=df2), colour="red") +
ggtitle('Df1 versus Df2') +
  ylab('Values') + xlab('Visits') + 
  theme(plot.title = element_text(hjust = 0.5))

标签: rggplot2

解决方案


像这样的东西?

library(tidyverse) # for ggplot and dplyr-stuff

library(data.table) # for fread and melt

df1 <- fread('no  df1
1  0.03789634
2  0.24012665
3  0.33449574
4  0.28389631
5  0.27714124
6  0.27867639
7  0.35170168
8  0.32454339
9  0.20677891
10 0.34182049')

df2 <- fread('no df2
1      0.07975460
2      0.08639309
3      0.07079646
4      0.08163265
5      0.08139535
6      0.10379747
7      0.09550562
8      0.07961783
9      0.09225092
10     0.09090909')

right_join(df1, df2) %>% melt(id.vars = 'no') %>%
  ggplot(aes(x = no,y = value, color = variable)) +
  geom_line() +
  ggtitle('Df1 versus Df2') +
  ylab('Values') + xlab('Visits') + 
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_color_manual(values = c('blue', 'red'))


推荐阅读