user3227546
user3227546

Reputation:

How do I add colours to a stacked bar graph in R?

I am trying to create a stacked bar graph in R. I need the bar graph to display three things:

So my desired output is: Desired Output

However, my actual output is:

Actual output

My code so far is:

carData <- read.csv(file="~/Desktop/carData.csv",head=TRUE,sep=";")
ggplot(carData, aes(x =  passed.test, fill =  owns.car)) + geom_bar() 

The passed.test values in the CSV file are either 1 or 0. (1 = passed ,0 = not passed)

The owns.car values in the CSV file are either 1 or 0. (1 = owns a car, 0 = doesn't own a car)

How do I:

A. Add colours to the bar graph to show the second variable (Owns a car = Yes or No)

B. Change the X axis to be 'Yes' and 'No', rather than -0.5 -1.5

Upvotes: 0

Views: 105

Answers (1)

camille
camille

Reputation: 16832

You want to make both those columns into factors. Otherwise, numeric values are assumed to be continuous, so when geom_bar counts observations of each value, it doesn't make a whole lot of sense for the levels of owns.car to be continuous.

library(tidyverse)

set.seed(1234)
carData <- tibble(
    passed.test = sample(c(0, 1), 100, replace = T),
    owns.car = sample(c(0, 1), 100, replace = T)
)

cars_factors <- mutate_all(carData, as.factor)

ggplot(cars_factors, aes(x = passed.test, fill = owns.car)) +
    geom_bar() +
    scale_x_discrete(labels = c("No", "Yes")) +
    scale_fill_discrete(labels = c("No", "Yes"))

Created on 2018-04-28 by the reprex package (v0.2.0).

Upvotes: 2

Related Questions