r - 如何使用 facet_wrap 或 facet_grid 对绘图进行刻面?
问题描述
我有一个包含 4 列(year、high_yield、us_bond、us_stock)的数据框(称为“dat”),我想创建一个分面图来显示三种投资方法(high_yield 、us_bond 和 us_stock)。我能做些什么?
year high_yield us_bond us_stock
1 0 1000.000 1000.000 1000.000
2 1 1220.586 1281.926 1283.605
3 2 1450.444 1520.894 1215.798
4 3 1692.547 1717.119 1745.844
5 4 1943.387 1986.865 2541.729
6 5 2208.077 2311.152 2144.041
7 6 2485.897 2462.264 2550.917
8 7 2777.211 2882.419 3264.006
9 8 3082.773 3081.522 2653.898
10 9 3392.857 3740.678 3421.683
11 10 3723.774 3916.913 3910.493
解决方案
您可以使用以下代码来完成此操作
library(data.table)
df=data.frame(year=seq(0,10,1), high_yield=c(1000.000, 1220.586, 1450.444, 1692.547, 1943.387, 2208.077, 2485.897, 2777.211, 3082.773,3392.857,3723.774),
us_bond=c(1000.000, 1220.586, 1450.444, 1692.547, 1943.387, 2208.077, 2485.897, 2777.211, 3082.773, 3392.857, 3723.774),
us_stock=c(1000.000, 1220.586, 1450.444, 1692.547, 1943.387, 2208.077, 2485.897, 2777.211, 3082.773, 3392.857, 3723.774))
df.m = melt(df, id.vars = c("year"),
measure.vars = c("high_yield", "us_bond", "us_stock"))
library(ggplot2)
bp <- ggplot(df.m, aes(x=year, y=value, group=variable)) +
geom_line(color = "steelblue",size = 1)
bp + facet_grid( .~ variable, scales='free') +
geom_point(color="steelblue") +
labs(y = "Value of investment", x = "Year")
我对 high_yield、us_bond 和 us_stock 使用了相同的数据集。
推荐阅读
- c# - 为什么使用 WebClient 的 UploadFileAsync 没有错误通知?
- ios - 具有关联类型作为属性的协议
- html - CSS:两个文本并排,一个适合内容,另一个缩小并溢出,直到最小宽度然后换行
- xslt - Apache-FOP 换行符
- javascript - Rails使用表单对象渲染部分
- python - 预测二元分类
- java - 确定任务是否更早,同时仅知道日期是否更早以及时间是否更早
- mysql - 在这种情况下,我应该使用带有布尔标志的多对多表还是一个表?
- javascript - 未捕获的类型错误:(中间值)(中间值)(中间值)不是函数
- c - 如何检查单词b(C lang)中单词a中的所有字符?