Ryan
Ryan

Reputation: 1432

How Can I Plot Percentage Change for 3 Vectors in Same DataFrame?

I have three vectors and a list of crimes. Each crime represents a row. On each row, each vector identifies the percentage change in the number of incidents of each type from the prior year.

Below is the reproducible example. Unfortunately, the df takes the first value in and repeats in down the columns (this is my first sorta reproducible example).

crime_vec = c('\tSTRONGARM - NO WEAPON', '$500 AND UNDER', 'ABUSE/NEGLECT: CARE FACILITY', 'AGG CRIM')
    change15to16vec = as.double(825, -1.56, -66.67, -19.13)
    change16to17vec = as.double(8.11, .96, 50, 4.84)
    change17to18vec = as.double(-57.50, 1.29, 83.33, 28.72)
    df = data.frame(crime_vec, change15to16vec, change16to17vec, change17to18vec)
    df

I need a graph that will take the correct data frame, show the crimes down the y axis and ALL 3 percentage change vectors on the x-axis in a dodged bar. The examples I've seen plot only two vectors. I've tried plot(), geom_bar, geom_col, but can only get one column to graph (occasionally).

Any suggestions for a remedy would help.

Upvotes: 0

Views: 119

Answers (1)

Martin Gal
Martin Gal

Reputation: 16988

Not sure if this is what you are looking for:

library(tidyr)
library(ggplot2)

df %>% 
  pivot_longer(-crime_vec) %>% 
  ggplot(aes(x = value, y = crime_vec, fill = as.factor(name))) + 
  geom_bar(stat = "identity", position = "dodge") +
  theme_minimal() +
  xlab("Percentage Change") + 
  ylab("Crime") + 
  labs(fill = "Change from")

For using ggplot2 it's necessary, to bring your data into a long format. geom_bar should create your desired plot.

Upvotes: 1

Related Questions