Home > Software design >  Plot graph based on condition from another column in R
Plot graph based on condition from another column in R

Time:03-29

I have dataset which looks like this:

CrimeRate   Southern
56.6            1
60.3            1
79.8            1
85.6            0
96.8            0
97.4            0
98.7            1
99.9            1
103             1
106.6           1
109.4           1
112.1           0
114.3           0
121.6           1
123.4           1
145.4           1

where 1 means Southern and 0 means Non southern.

I want to use graph, to compare the crime rates in southern and non-southern states.

Here's my code so far but I'm getting errors , How do I plot graph?

compare_crime <- aggregate(crimeData$crime_rate ~ crimeData$southern, data=crimeData, FUN=sum)
hist(compare_crime)

CodePudding user response:

Here is one option:

library(tidyverse)

ggplot(df, aes(x=factor(Southern), y=CrimeRate))  
    geom_bar(stat="identity") theme_minimal()

Output

enter image description here

Or if you want a histogram, then you can do something like this:

library(hrbrthemes)

ggplot(df, aes(x=CrimeRate, fill=factor(Southern)))  
  geom_histogram( color="#e9ecef", alpha=0.6, position = 'identity')  
  scale_fill_manual(values=c("#69b3a2", "#404080"))  
  theme_ipsum()  
  labs(fill="")

Output

enter image description here

Data

crimeData <- structure(list(CrimeRate = c(56.6, 60.3, 79.8, 85.6, 96.8, 97.4, 
98.7, 99.9, 103, 106.6, 109.4, 112.1, 114.3, 121.6, 123.4, 145.4
), Southern = c(1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 
0L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA, -16L
))
  • Related