r - 使用 R ggplot2:如何使用 ggplot2 诱导 BROKEN Y-AXIS 图:Y 轴坐标 0:1000 然后 15000:31000
问题描述
我想将 Y 轴分成两部分,并使用 ggplot2 在 Y 轴中引入中断。Y轴坐标:[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])
解决方案
故意很难得到类似于中断轴的东西,因为它们很容易被用来歪曲数据。也就是说,您可以通过以下解决方法获得类似于 y 轴中断的东西。
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())
现在这是我认为你实际上应该做的,而不是试图让轴中断:
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()