[英]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: 我正在尝试在R中创建一个堆叠的条形图。我需要该条形图显示三件事:
So my desired output is: 所以我想要的输出是:
However, my actual output is: 但是,我的实际输出是:
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) CSV文件中的pass.test值为1或0。(1 =已通过,0 =未通过)
The owns.car values in the CSV file are either 1 or 0. (1 = owns a car, 0 = doesn't own a car) CSV文件中的owns.car值为1或0。(1 =拥有汽车,0 =不拥有汽车)
How do I: 我如何:
A. Add colours to the bar graph to show the second variable (Owns a car = Yes or No) A.在条形图中添加颜色以显示第二个变量(拥有汽车=是或否)
B. Change the X axis to be 'Yes' and 'No', rather than -0.5 -1.5 B.将X轴更改为“是”和“否”,而不是-0.5 -1.5
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. 否则,数值被认为是连续的,所以当geom_bar
每个值的计数观测,它不会使整个很大的意义的水平owns.car
是连续的。
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). 由reprex软件包 (v0.2.0)创建于2018-04-28。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.