简体   繁体   中英

How to facet a plot using facet_wrap or facet_grid?

I have a data frame (called "dat") with 4 columns (year, high_yield, us_bond, us_stock) and I want to create a facet plot to show how the value of investment changes over year for each of the three investment method (high_yield, us_bond, and us_stock). What can I do?

   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

You can use the following code to accomplish that

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

在此处输入图像描述

I have used same dataset for high_yield, us_bond and us_stock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM