r - 用手动图例绘制两个数据框
问题描述
我是 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))
解决方案
像这样的东西?
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'))
推荐阅读
- python - Pandas 将特定列转换为列表
- twain - 强制终止 WIA 或 TWAIN 驱动程序(扫描仪)
- angular - HttpInterceptor 在 Angular 6 中不起作用
- java - okhttp 中的代理问题
- sql - 有哪些带有图形查询设计器的 SQL 客户端..?
- angular - 使链中的第一个可观察对象成为可选的
- c# - 带静态类的循环引用项目
- python - (1064, "您的 SQL 语法有错误;.. 在第 1 行的 '%s, %s, %s, %s, %s)' 附近使用正确的语法")
- javascript - 如何在两者之间渲染 JSX 代码
标签
- c# - Entity Framework 6 Code First - 将函数或 StoredProc 映射到原始类型