我有这个数据
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))
直到现在,我已经使用以下代码创建了此图表:
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 在我的图表中,没有城市,而是“全州”,“白色”,“黑色”和“西班牙裔”。另外,我的表将有几年(从2015年到2017年),而不是几个月。我不需要季节或“冻结”线。我只想像他们一样添加图例和表格。
答案 0 :(得分:3)
关于图例,这不是xliffmerge
方式。将您的数据从宽到长转换,然后将ggplot
键映射到颜色,作为美观的映射。
what
关于表格,这似乎有点像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
剩下要做的就是抛光一些最终的人物。
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)