How to put captions on a line chart in ggplo2

Asked

Viewed 129 times

2

I have a line chart with two variables and I need to put the caption of each one, however, I’m not getting.

I’m using a code like this:

library(ggplot2)

data <- c(1:50)
dado <- c(1:50)
dado1 <- c(1:25)

dados <- data.frame(Data = data, "1" = dado, "2" = dado1)

ggplot(data = dados) +
  geom_line(aes(x = Data, y = X1), color = "blue") +
  geom_line(aes(x = Data, y = X2), color = "red") +
  labs(x = "Dado", y = "Dado2", color = "Casos") +
  ggtitle("Teste")

How can I define the legend of each variable? With labs, it only plots the caption of the X and Y axes.

1 answer

4


The best way to plot data the way you want is to put it in the long format. Read this question right here at Stackoverflow to find out what this is. In short, you need to create a column in your dataset that identifies the different X1 and X2 cases. The function melt package reshape2 does this automatically:

library(ggplot2)
library(reshape2)

data <- c(1:50)
dado <- c(1:50)
dado1 <- c(1:25)

dados <- data.frame(Data = data, "1" = dado, "2" = dado1)

dados <- melt(dados, id.vars = "Data")

head(dados)
#>   Data variable value
#> 1    1       X1     1
#> 2    2       X1     2
#> 3    3       X1     3
#> 4    4       X1     4
#> 5    5       X1     5
#> 6    6       X1     6

There is no need to rename columns. It would be possible to keep Data, variable and value. I changed the names for teaching purposes.

names(dados) <- c("Data", "Casos", "Valor")

head(dados)
#>   Data Casos Valor
#> 1    1    X1     1
#> 2    2    X1     2
#> 3    3    X1     3
#> 4    4    X1     4
#> 5    5    X1     5
#> 6    6    X1     6

ggplot(data = dados, aes(x = Data, y = Valor, color = Casos)) +
    geom_line() +
    labs(x = "Dado", y = "Dado2", color = "Casos") +
    ggtitle("Teste")

Created on 2020-04-23 by the reprex package (v0.3.0)

Some of the great advantages of using data in long format are

  • use the package functions dplyr where it wishes to carry out groupings of data from the column Casos
  • type less code; imagine if there were 10 lines to be plotted and you had to type geom_line 10 times?
  • the legend is built automatically
  • easily change the color palette of the created chart
ggplot(data = dados, aes(x = Data, y = Valor, color = Casos)) +
    geom_line() +
    labs(x = "Dado", y = "Dado2", color = "Casos") +
    ggtitle("Teste") +
    scale_color_brewer(palette = "Dark2")

inserir a descrição da imagem aqui

Created on 2020-04-23 by the reprex package (v0.3.0)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.