1

I have a Excel spread sheet with which looks at the relationship between victim and offender in murders. Either the murderer know the victim or not.

enter image description here

I want to plot it in a barplot, but I need to group each year. I am a bit green in R graphing so I did a paint image of what I want to have in my report:

enter image description here

I have the following code:

# Libraries
library("readxl")

res <- readxl::read_excel("muders_in_norway_with_relations.xlsx", sheet = 1)

dput(head(res[, 1:3])) 

# Plot bar
barplot(`Relation`~`2019`, res,
        main = "Murders in Norway with relations",
        xlab = "Year",
        ylab = "Murders")


which outputs this:

## structure(list(Relation = c("Relations", "No relation"), `2019` = c(26, 
## 3), `2020` = c(30, 1)), row.names = c(NA, -2L), class = c("tbl_df", 
## "tbl", "data.frame"))

Maby I am doing something wrong when I am reading the data into R?

2
  • is your "res" a dataframe object? Commented May 14, 2021 at 11:51
  • res is from Excel. Im not sure what a dataframe object is. Commented May 14, 2021 at 11:58

1 Answer 1

1

I did this:

library(data.table)    
library(ggplot2)
a = matrix(c(26,30,3,1),ncol=2,byrow = T)
a= as.data.frame(a)
a$r = c('relation', 'no relation')
colnames(a )=c('2019','2020','r')
a= melt(a)
ggplot(a, aes(fill=r,x=variable,y=value))+
  geom_bar(stat="identity", position=position_dodge(), width = 0.5)+
  theme_classic()+
  scale_fill_manual(values = c('blue','red'))

Maybe in your case you can do this:

library("readxl")
library(data.table)
library(ggplot2)
res <- as.data.frame(readxl::read_excel("murders_in_norway_with_relations.xlsx", sheet = 1))
res$r = c('relation','No relation')
res=reshape::melt(res)
ggplot(res, aes(fill=r,x=variable,y=value))+
geom_bar(stat="identity", position=position_dodge(), width = 0.5)+
theme_classic()+
scale_fill_manual(values = c('blue','red'))

Does it make the job?

enter image description here

Sign up to request clarification or add additional context in comments.

6 Comments

Error in melt(a) : Could not find function melt. Also, I need to read the data from Excel.
Sorry melt is from the data.table package so you need to do library(data.table) before
And you can create the last column for my code coming from your dataframe using: res$r=rownames(res)
Does it work with the second code I added?
The melt gives error: Error in value [[3L]](cond) : The melt generic in data.table has been passed a data.frame, but data.table::melt currently only has a method for data.tables. Please confirm your input is a data.table, with SetDT(res) or as.data.table(res).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.