如何使用ggplot2将图例和具有数据值的表添加到具有不同线条的图表中

时间:2018-12-12 23:43:12

标签: r ggplot2 statistics visualization

我有这个数据

TX_growth<-data.frame(year=c(2017,2016, 2015),statewide=c(61, 62,57),black=c(58,58,53),hispanic=c(59,60,55),white=c(65,64,61))

直到现在,我已经使用以下代码创建了此图表:

My chart until now enter image description here

    ggplot() + geom_line(data = TX_growth, aes(x=year, y= statewide), color = "blue", size=1) + 
    geom_line(data = TX_growth, aes(x=year, y= white), color = "red", size=1) + 
    geom_line(data = TX_growth, aes(x=year, y= black), color = "green", size=1) + 
    geom_line(data = TX_growth, aes(x=year, y= hispanic), color = "orange", size=1) + 
    labs(title = "Figure 1: Statewide Percent who Met or Exceeded Progress", 
         subtitle = "Greater percentage means that student subgroup progressed at higher percentage than previous year.", 
         x = "Year", y = "Percentage progress")+ theme_bw() + 
    scale_x_continuous(breaks=c(2017,2016,2015)) 

我想添加(a)显示每行名称和颜色的图例,以及(b)包含我的数据框所有值的下表。像这样:

What I want enter image description here 在我的图表中,没有城市,而是“全州”,“白色”,“黑色”和“西班牙裔”。另外,我的表将有几年(从2015年到2017年),而不是几个月。我不需要季节或“冻结”线。我只想像他们一样添加图例和表格。

1 个答案:

答案 0 :(得分:3)

第1部分-修复图例

关于图例,这不是xliffmerge方式。将您的数据从宽到长转换,然后将ggplot键映射到颜色,作为美观的映射。

what

enter image description here

第2部分-添加表格

关于表格,这似乎有点像Adding a table of values below the graph in ggplot2的副本。

要总结各种文章,我们可以使用library(tidyverse) TX_growth %>% gather(what, value, -year) %>% ggplot() + geom_line(aes(x=year, y= value, colour = what), size=1) + labs( title = "Figure 1: Statewide Percent who Met or Exceeded Progress", subtitle = "Greater percentage means that student subgroup progressed at higher percentage than previous year.", x = "Year", y = "Percentage progress") + theme_bw() + scale_x_continuous(breaks=c(2017,2016,2015)) 在底部添加表格;这是一个最小的示例:

egg::ggarrange

enter image description here

剩下要做的就是抛光一些最终的人物。

第3部分-经过抛光...

library(tidyverse)
gg.plot <- TX_growth %>%
    gather(what, value, -year) %>%
    ggplot() +
        geom_line(aes(x=year, y= value, colour = what), size=1) +
        theme_bw() +
        scale_x_continuous(breaks=c(2017,2016,2015))

gg.table <- TX_growth %>%
    gather(what, value, -year) %>%
    ggplot(aes(x = year, y = as.factor(what), label = value, colour = what)) +
        geom_text() +
        theme_bw() +
        scale_x_continuous(breaks=c(2017,2016,2015)) +
        guides(colour = FALSE) +
        theme_minimal() +
        theme(
            axis.title.y = element_blank())

library(egg)
ggarrange(gg.plot, gg.table, ncol = 1)

enter image description here