Как добавить легенду и таблицу со значением данных в диаграмму с разными линиями, используя ggplot2 - PullRequest
0 голосов
/ 13 декабря 2018

У меня есть эти данные

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

До сих пор у меня есть этот график, используя следующий код:

Мой график до сих пор 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)) 

Я хочу добавить (а) легенду, показывающую имя и цвет каждой строки и (б) таблицу ниже со всеми значениями моего информационного кадра.Примерно так:

То, что я хочу enter image description here Вместо городов на моем графике будут "Statewide", "White", "Black" и "Испанец».Кроме того, мой стол будет иметь годы (с 2015 по 2017 год), а не месяцы.Я не хочу сезонов или "заморозки" линии.Я просто хочу добавить легенду и таблицу, как они это сделали.

1 Ответ

0 голосов
/ 13 декабря 2018

Часть 1 - Исправление легенды

Что касается легенды, то это не ggplot путь.Преобразуйте данные из широкого в длинный, а затем сопоставьте клавиши what с цветом в качестве эстетического сопоставления.

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

enter image description here

Часть 2- Добавление таблицы

Что касается таблицы, это выглядит как дубликат Добавление таблицы значений под графиком в ggplot2 .

Подводить итог из различныхпосты, мы можем использовать 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)

enter image description here

Все, что остается сделать, - это окончательная полировка фигуры.

Часть 3 -После некоторой полировки ...

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

gg.table <- TX_growth %>%
    gather(Group, value, -year) %>%
    ggplot(aes(x = year, y = as.factor(Group), label = value, colour = Group)) +
        geom_text() +
        theme_bw() +
        scale_x_continuous(breaks = 2015:2017) +
        scale_y_discrete(position = "right") +
        guides(colour = FALSE) +
        theme_minimal() +
        theme(
            axis.title.y = element_blank(),
            axis.title.x = element_blank(),
            axis.text.x = element_blank(),
            panel.grid.major = element_blank(),
            panel.grid.minor = element_blank())

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

enter image description here

...