How to put lines on a chart and bar?

Asked

Viewed 170 times

-4

I’d like to know how to insert lines in a bar graph.

I have the following code:

Periodo <- c("01/2020", "03/2020", "05/2020",
            "06/2020", "08/2020", "09/2020")
Valores <- c("0,08", "3,15", "4,91", "0,72", "6,21", "8,80")

teste <- data.frame(Periodo, Valores)

library(ggplot2)

ggplot(teste) + aes(x = Periodo, y = Valores) + geom_bar(stat='identity')
  • Change your question to: How to add lines to the chart and how to turn a column into numerical data.

2 answers

0

I’d like to know how to insert lines in a bar graph.

You can insert lines using geom_line():

ggplot(teste, aes(x = Periodo, y = Valores, group = 1)) + 
  geom_bar(stat='identity') +
  geom_line()

-1


The main problem seems to be the vector Valores be a class vector "character", the numbers are strings, without any numerical value. This can be seen by the yy axis, whose annotations are equidistant although the values are not equidistant. Differences from one value to the other are not constant but the difference in bar heights is always the same.

To have the right graph, you have to transform the vector Valores in numerical vector, replacing first the commas with dots.

The final chart shows the two charts side by side with the package gridExtra, in order to better see the difference.

library(ggplot2)

Periodo <- c("01/2020", "03/2020", "05/2020",
             "06/2020", "08/2020", "09/2020")
Valores <- c("0,08", "3,15", "4,91", "0,72", "6,21", "8,80")

teste <- data.frame(Periodo, Valores)

g1 <- ggplot(teste, aes(x = Periodo, y = Valores, group = 1)) + 
  geom_bar(stat='identity') +
  geom_line() +
  ggtitle("Gráfico original")

Valores <- as.numeric(sub(",", ".", Valores))
teste <- data.frame(Periodo, Valores)

g2 <- ggplot(teste, aes(x = Periodo, y = Valores, group = 1)) + 
  geom_bar(stat='identity') +
  geom_line() +
  ggtitle("Gráfico depois de 'as.numeric/sub'")

gridExtra::grid.arrange(g1, g2, nrow = 1, ncol = 2)

inserir a descrição da imagem aqui

Browser other questions tagged

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