EN VI

how to add minor axis and remove major axis by ggplot2?

2024-03-15 22:00:07
how to add minor axis and remove major axis by ggplot2?

I have the following two questions: (1) I want to get the label to be between two ticks. My original thought was to add the secondary ticks and remove the primary ticks, but axis.minor.ticks.length.y doesn't work (2) Add stat_summary points at the legend Thank you very much for answering your questions!

Here is the code and figure:

library("ggplot2")
dt <- data.frame(
  ca = rep(c("Oesophageal cancer", "Gastric cancer", "Colorectal cancer"), 3),
  var1 = c(1:3, -4:-6, 7:9),
  var2 = rep(LETTERS[1:3], 3)
)

dt %>% 
  ggplot(aes(var1, ca, fill = var2))+
  geom_bar(stat="identity", width=0.8)+
  stat_summary(fun=sum, geom="point",colour="grey40", fill="grey40", shape=20, size=2)+
  geom_vline(xintercept=0, colour="grey30", linetype="dotted")+
  theme(
    axis.minor.ticks.length.y = rel(0.5)
  )

Objective: Change Figure 1 to Figure 2 style Figure 1 Figure 2

Solution:

You need to convert to a continuous scale to use minor ticks, since there are no minor breaks on a discrete axis:

dt %>% 
  ggplot(aes(var1, as.numeric(factor(ca)), fill = var2)) +
  geom_col(width = 0.8, orientation = 'y') +
  stat_summary(orientation = 'y', fun = sum, geom = "point", colour = "grey40", 
               fill = "grey40", aes(shape = 'average'), size = 2) +
  geom_vline(xintercept=0, colour="grey30", linetype = "dotted") +
  scale_y_continuous('ca', labels = levels(factor(dt$ca)), 
                     breaks = seq_along(levels(factor(dt$ca)))) +
  scale_shape_manual(NULL, values = 20) +
  guides(y = guide_axis(minor.ticks = TRUE), 
         fill = guide_legend(order = 1),
         shape = guide_legend(order = 2)) +
  theme(axis.minor.ticks.length.y = unit(3, 'mm'),
        axis.ticks.length.y = unit(0, 'mm'),
        legend.key = element_blank())

enter image description here

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login