0

I am seeing the suicide toll in Spain, the data its separated by years locate in columns. 1-14 years / 15-30 years/ 30-39 years...

And separated by genre. Masculine/Femenine/All

this is the .csv: Link to csv in Gdrive

I can plot with geom_point with this code:

library(tidyverse)
library(dplyr)

suicidio<- read.csv("C:/Users/BlackMamba/Desktop/xy/suicidio2.csv", encoding = "ASCII", header = TRUE, sep = ";")
colnames(suicidio) <- c("genero","total", "uno", "a14", "a1529", "a3039", "a4044", "a4549", "a5054", "a5559", "a6064","a6569", "a7074", "a7579","a8084","a8590","a9094","95")

ggplot(suicidio,aes (x=genero))+
  geom_point (aes(y = a1529), color = "red" , size=3)+
  geom_point (aes(y = a3039), color = "black" ,size=3)+
  geom_point (aes(y = a3039), color = "green", size=3)+
  geom_point (aes(y = a4044), color = "blue", size=3)+
  geom_point (aes(y = a4549), color = "grey", size=3)+
  geom_point (aes(y = a5054), color = "pink" ,size=3)+
  geom_point (aes(y = a5559), color = "orange" ,size=3)+
  geom_point (aes(y = a6064), color = "brown" ,size=3)+
  geom_point (aes(y = a6569), color = "steelblue", size=3)

But I want to plot with bars, and obtain the Legend with the colors for each year, Is it possible?

I have another question. In colnames row I have tried with names like "1-14", "14-30" but the ggplot can't plot these, I have to rename with letters. I can't call "colnames" with numbers?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Raul
  • 139
  • 9
  • 3
    You can use `pivot_longer` to move collect your age columns together as discussed here: https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format – Greg Jun 17 '20 at 13:28

1 Answers1

2

An explicit example for you:

s2 <- suicidio %>% 
  pivot_longer(cols = c("uno", "a14", "a1529", "a3039", "a4044", "a4549", "a5054", 
                        "a5559", "a6064","a6569", "a7074", "a7579","a8084","a8590","a9094","95"),
               values_to = "Value", names_to = "Age_Group")

ggplot(s2,aes (x=genero, y = Value))+
  geom_bar(aes(fill=Age_Group), stat="identity", position = "dodge") +
  scale_fill_manual(values = colors()[1:16])

If you want a stacking plot, you can remove position="dodge", colors can be adjusted by scale_fill_manual

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
SebSta
  • 476
  • 2
  • 12