ggplot2绘制两组不同比例的两个变量

时间:2018-11-08 17:49:59

标签: r ggplot2

我具有以下形式的数据框:

School_type     Year    fund  rate  
    1           1998    8     0.1
    0           1998    7     0.2
    1           1999    9     0.11
    0           1999    8     0.22
    1           2000    10    0.12
    0           2000    15    0.23

我正在考虑绘制每种学校类型的“资金”和“费率”,而x轴是年份,所以有四行-两条较高的线和两条较低的线,但是我不知道如何用两个比例的y轴来实现。预先感谢。

1 个答案:

答案 0 :(得分:0)

我不确定这是否是您要寻找的东西,但这是我的两分钱。

#create the dataframe
df = data.frame("school_type" = 0:1, "year" = c("1998","1998","1999","1999","2000","2000"), 
            "fund" = c("8","7","9","8","10","15"), "rate" = c("0.1","0.2","0.11","0.22","0.12","0.23"))

#Modify the variable typr
df$fund = as.numeric(as.character(df$fund))
df$rate = as.numeric(as.character(df$rate))

#plot the log of the variables
df %>%
mutate(log_fund = log(fund),
     log_rate = log(rate)) %>%
melt(id.vars = c("school_type","year")) %>%
filter(variable %in% c("log_fund","log_rate")) %>%
ggplot(aes(x = year, y = value, group = variable, color = variable, shape = variable)) +
geom_line(size = 1) +
geom_point(size = 3) +
facet_wrap(~ school_type) +
theme_bw()

结果:here