简体   繁体   中英

Using R ggplot2: How to induce BROKEN Y-AXIS plot using ggplot2: Y axis coordinates 0:1000 then 15000: 31000

I want to break Y-axis into two parts and introduce breaks in the Y axis using ggplot2. The coordinates of Y-axis: [0,500,1000,1500,break,12000,17000,22000,27000,32000]

INPUT DATAFRAME

    least_dist frequency           category
          250        444  Without Inhibitor
          500        489  Without Inhibitor
           1k        697  Without Inhibitor
           2k        305  Without Inhibitor
          >2k      15742  Without Inhibitor
          250        284     With Inhibitor
          500        313     With Inhibitor
           1k        501     With Inhibitor
           2k        337     With Inhibitor
          >2k      32727     With Inhibitor
#My Code
df = read.csv('peaks_least_distant.table',sep="\t",header = T)

p<-ggplot(df,aes(x=least_dist, y=frequency,fill = category))+
  geom_bar(stat="identity",position=position_dodge())+
  scale_fill_brewer(palette="Paired")+
  theme_minimal()
p+scale_y_continuous(breaks=c[500:1500,'Break',12000:32000])

It is deliberately very difficult to get something to resemble interrupted axes, because they are so easily used to misrepresent the data. That said, here is how you can have a workaround to get something resembling y-axis breaks.

cutoff <- 1500

# Copy part of data above break
df2 <- df[df$frequency > cutoff,]

# Assign panels
df$panel  <- factor("lower", levels = c("upper", "lower"))
df2$panel <- factor("upper", levels = levels(df$panel))

# Cut off y-values in lower panel
df$frequency <- pmin(df$frequency, cutoff)

# Plot
ggplot(df,aes(x=least_dist, y=frequency,fill = category))+
  # Friendly reminder that 'geom_col' is the more convenient 'geom_bar(stat = "identity")'
  geom_col(position=position_dodge())+
  # Parameterise the upper part as rectangles
  geom_rect(aes(xmin = as.numeric(least_dist) - 0.45, xmax = as.numeric(least_dist) + 0.45,
                ymin = 12000, ymax = frequency), 
            data = df2,
            position = position_dodge()) +
  scale_fill_brewer(palette="Paired")+
  # Use facets to resemble an axis interruption
  facet_grid(panel ~ ., scales = "free_y") +
  theme_minimal() +
  # Hide away evidence of facetting
  theme(strip.text = element_blank())

在此处输入图像描述

Now here is what I think you actually should do instead of trying to have axis breaks:

ggplot(df,aes(x=least_dist, y=frequency,fill = category))+
  geom_col(position=position_dodge())+
  scale_fill_brewer(palette="Paired")+
  # A simple and elegant log transformation
  scale_y_log10() +
  theme_minimal()

在此处输入图像描述

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