Home > database >  unable to show axis tick label in ggplot in R
unable to show axis tick label in ggplot in R

Time:06-14

I'm trying to plot a stacked bar chart with ggplot. Below is my code:

df = data.frame(Y = c(0,0,1,1), X = c(0,1,0,1), N = c(200, 50, 300, 70))

ggplot(data=df, aes(y=N, x= X, fill=Y))   
                geom_bar(position="stack", stat="identity", width=0.7) 
                scale_x_discrete(name ="", breaks = c(0, 1), labels=c("No",'Yes'))  
                theme(legend.position="none")

I want to show 'No' and 'Yes' as tick label on x axis. But nothing shows up. Does anyone know why my tick labelz do not show up? I do not understand what I did wrong.

CodePudding user response:

An easier way to do it may be to do the data transformation outside the ggplot function:

library(ggplot2)
library(dplyr)

df = data.frame(Y = c(0,0,1,1), X = c(0,1,0,1), N = c(200, 50, 300, 70))
df %>% 
  mutate(X = if_else(X == 0, "No", "Yes")) %>% 
  ggplot(aes(y=N, x= X, fill=Y))   
  geom_bar(position="stack", stat="identity", width=0.7) 
  theme(legend.position="none")

CodePudding user response:

You just need to insert factor(X) to make X discrete rather than continuous:

library(tidyverse)

df <- data.frame(Y = c(0, 0, 1, 1), X = c(0, 1, 0, 1), N = c(200, 50, 300, 70))

ggplot(data = df, aes(y = N, x = factor(X), fill = Y))  
  geom_bar(position = "stack", stat = "identity", width = 0.7)  
  scale_x_discrete(name = "", breaks = c(0, 1), labels = c("No", "Yes"))  
  theme(legend.position = "none")

Created on 2022-06-14 by the reprex package (v2.0.1)

  • Related