简体   繁体   English

R 中的条形图:如何在条形图中使用空值添加条形图

[英]Barplot in R: how to add bar in barplot with empty value

I want to create a barplot with in axis x 'yes' and 'no' and in axis y the variable of answers given on the question.我想创建一个条形图,其中 x 轴为“是”和“否”,y 轴为问题给出的答案变量。 My issue is that the dataset doesn't contain any answers with 'Yes' Therefore the bar for 'yes' is left out.我的问题是数据集不包含任何带有“是”的答案,因此“是”栏被省略了。 Nonetheless I still want a bar for 'yes' even when the given value will be 0尽管如此,即使给定值为 0,我仍然想要一个“是”栏

# Set figure values 
a <- 1.2 # Set size of titles
b <- 1.2 # Set size of categories
c <- 1.8 # Set size of axis
d <- rgb(204/255,0,51/255) # Set the colour of the bars
e <- c(0,50) # Set the boundary for the y-axis
h <- c(0,80) # Set the boundary for the y-axis

plot(factor(df$slachtoffer.3.[df$startvraag=="Ja"]), cex = b, cex.axis = c, las=1, col = d, ylim = h, yaxt = "n", family = "Open Sans")
title(main = title[10], cex.main = a, family = "Open Sans")
axis(2, at = seq(0, 80, by = 10), las = 1, tck = -.02, cex.axis = b, family = "Open Sans")

I've also tried below but this removes the whole X axis.我也在下面尝试过,但这会删除整个 X 轴。

plot(factor(df$slachtoffer.3.[df$startvraag=="Ja"], exclude = "N/A"), levels = c("Ja", "Nee"), labels = c("Ja", "Nee"), cex = b, cex.axis = c, las=1, col = d, ylim = h, yaxt = "n", family = "Open Sans")
title(main = title[10], cex.main = a, family = "Open Sans")
axis(2, at = seq(0, 80, by = 10), las = 1, tck = -.02, cex.axis = b, family = "Open Sans")

The data being used for the plots is plain 'yes' and 'no' answers which were given on questions during an interview.用于绘图的数据是简单的“是”和“否”答案,这些答案是在采访期间对问题给出的。 So for example: df$slachtoffer.3.例如:df$slachtoffer.3。 is only filled with the answer 'No'.只填写了“否”的答案。 This data should only be used when the previous question df$startvraag was answered with 'yes'.仅当上一个问题 df$startvraag 的回答为“是”时,才应使用此数据。

I am able to create different graphics where both 'yes' and 'no' are within the dataset.我能够创建不同的图形,其中“是”和“否”都在数据集中。 example graphic .示例图形 As you can see, when there is no 'yes' available in the dataset, it just removes the whole bar instead of adding it and setting the value at 0.如您所见,当数据集中没有可用的“是”时,它只会删除整个条形而不是添加它并将值设置为 0。

So my question is: How do I create a plot where both bars: Yes and No, are visable regardless of the variable?所以我的问题是:如何创建一个 plot 两个条:是和否,无论变量如何,都是可见的?

Here is a small example using packages from the tidyverse这是一个使用来自tidyverse的包的小例子

library(tidyverse)

dat <- tibble(res = c('No', 'No', NA, "No", "No")) %>% 
  mutate(res = as.factor(res))
  
levels(dat$res) <- c(levels(dat$res),"Yes")

ggplot(dat, aes(x = res)) +
  geom_bar() +
  scale_x_discrete(drop = FALSE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM