Double bar graph

Asked

Viewed 694 times

2

I am trying to make a double bar chart with the following data frame:

Total_CPIs <- data.frame(Período =c(1995, 1999, 2003, 2007, 2011), 
                SP = c(12, 11, 2, 20, 22), RS = c(3, 4, 2, 4, 4))

The column Período refers to the starting year of each Parliamentary Term; SP are the Cpis occurred in São Paulo and; RS the Cpis occurred in Rio Grande do Sul.

The idea is that in the end I have by Legislature the bars with the Cpis in each state and I would like to put on top of the bars the total amount (number) of Cpis. Can someone give me a light on how to get this chart?

2 answers

3

The best way to do what the question asks is to use the package ggplot2.
I’ll still use the package reshape2 to reformat data from wide format to long format.

library(ggplot2)

longo <- reshape2::melt(Total_CPIs, id.vars = "Período")

ggplot(longo, aes(x = factor(Período), y = value, fill = variable)) +
  geom_bar(position = position_dodge(1), stat="identity") +
  geom_text(aes(y = value, label = value), vjust = -0.2,
            position = position_dodge(width = 1)) +
  xlab("Período")  +
  ylab("CPIs")

inserir a descrição da imagem aqui

1

I noticed that you asked a new question wondering how to work with the chart caption.

My suggestion is similar to that of the colleague, with some differences:

  1. The function used for reformatting the chart is the gather() package tidyr. Notice I called it UF the column with the states and, the way the graph was assembled, this will be the name of the legend.
  2. Includes the function scale_fill_manual(), in it you can customize the color of the bars.
  3. The Labels were included through the function labs(). Why? If you want to change the name of the states legend, just include the attribute fill = "Nome da Legenda"
library(ggplot2)
library(tidyr)

Total_CPIs <- data.frame(Período =c(1995, 1999, 2003, 2007, 2011), 
                         SP = c(12, 11, 2, 20, 22), RS = c(3, 4, 2, 4, 4))

df <- gather(Total_CPIs, "UF", "Valor", -Período)

ggplot(df, aes(x = factor(Período), y = Valor, fill = UF)) +
  geom_bar(stat = "identity", position = "dodge") +
  scale_fill_manual(values = c("red", "blue")) +
  labs(x = "Período", y = "CPIs")

inserir a descrição da imagem aqui

In short, in scale_fill_manual(), you can change the colors of the bars and in labs(), through the attribute fill, it is possible to change the label name. See the example below:

ggplot(df, aes(x = factor(Período), y = Valor, fill = UF)) +
  geom_bar(stat = "identity", position = "dodge") +
  scale_fill_manual(values = c("green", "lightblue")) +
  labs(x = "Período", y = "CPIs", fill = "Nome da Legenda")

inserir a descrição da imagem aqui

I hope I’ve helped.

Browser other questions tagged

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