简体   繁体   中英

geom_bar of count plot: add x axis label for column with no value and customize order of remaining bars

I need to add a label for the count of empty value in the below data:

library(ggplot2)
myData <- data.frame(
  x = c("A", "A", "B", "B", "B", "C", "C", "C", "", "", "", ""),
  y = c(1, 4, 1, 5, 1, 5, 6, 7, 3, 6, 6, 3)
)

ggplot(myData, aes(x=x)) + 
  geom_bar(width = 0.5)+
  geom_text(stat='count', aes(label = ..count..), vjust = -1)

My plot is currently like this: 在此处输入图像描述

How do I add a customized label for the first column? Say "Not Available"

Second question , I need to customize the order of the remaining bars, so the first bar is always the one with empty value, but subsequently, I want bars in this order B, C, A (not descending or ascending order). Other StackOverflow answers seem to address the re-ordering of bars based on counts.

you can do this by using scale_x_discrete, limits changes the order, label will decide what text you want to ave

p = ggplot(myData, aes(x=x)) + 
  geom_bar(width = 0.5)+
  geom_text(stat='count', aes(label = ..count..), vjust = -1)

p+scale_x_discrete(limits=c("","B","C","A"),
label=c("Not Available","B","C","A"))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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