用手动图例绘制两个数据帧

时间:2019-06-27 15:10:03

标签: r ggplot2

我是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))

1 个答案:

答案 0 :(得分:0)

像这样吗?

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'))

相关问题