使用 geom_col 更改 ggplot 的轴中断/限制

问题描述

我在更改条形图中的轴刻度时遇到问题。我刚开始使用 ggplot,所以答案可能很明显。

这是一些数据(是的,这很奇怪,但旨在模仿我拥有的原始数据集,我不允许共享):

lab='this is just a very long example text and it will be longer and longer and longer and longer and longer and longer and longer and longer and longer and end'
number=1:20
n=unlist(lapply(number,paste,value=lab))
a=round(runif(n=20,min=-48000,max=-40000))
b=round(runif(n=20,max=-40000))
c=round(runif(n=20,max=-40000))
d=data.frame(cbind(n,a,b,c))
df=pivot_longer(d,cols=c('a','b','c'))
l1=round(as.numeric(min(df$value))/1000 )*1000+1000
l2=round(as.numeric(max(df$value))/1000 )*1000-1000
lim=seq(from=l1,to=l2,by=-1000)  
colScale <- scale_fill_manual(name = "n",values = c(rainbow(nrow(df)/3)))

我从中创建了一个条形图

p1=ggplot(df,aes(name,value,fill = as.factor(n))) +
  geom_col(position = "dodge",colour='black') +
  #scale_y_continuous(breaks = lim,labels = as.character(lim)) +
  coord_flip() +
  theme_bw() + 
  theme(axis.text.x=element_text(angle=90),axis.title.x=element_text(face='bold')) +
  theme(axis.text.y=element_text(angle=90,size=15)) +
  theme(legend.title=element_blank()) +
  labs(x = "",y="test") +
  colScale +
  guides(fill=guide_legend(ncol=1)) +
  ggtitle('something') +
  theme(plot.title = element_text(hjust = 0.5,size=20)) 

which is this

这基本上按照我的意愿工作,但是 x 轴的缩放非常令人不快。我想要的是一个轴,其中的中断和标签等于向量“lim”。我的理解是,应该可以通过在注释行中缩放相应的轴来做到这一点。但是当我尝试这个时,我收到错误“离散值提供给连续比例”。我试图将比例更改为“scale_y_discrete”,但随后刻度完全消失。我尝试了我能找到的所有方法,但没有任何效果,所以出了什么问题?

根据答案,我将绘图定义更改为:

p1=ggplot(df,as.numeric(value),colour='black') +
  scale_y_continuous(breaks = lim,size=20)) 

which produced this plot

现在我可以更改轴刻度,但该图看起来与第一个完全不同。我的目标是保持外观,即只显示条形图的顶部。

解决方法

我建议将 value 转换为 as.numeric(最好在 ggplot 之前,但您可以在其中进行,如下所示)并使用 coord_cartesian 指定“视图窗口”。您可能还会发现按照您想要的顺序指定轴更简单,而不是使用 coord_flip,后者通常是不必要的 since ggplot 3.3.0

ggplot(df,aes(as.numeric(value),name,fill = as.factor(n))) +
  geom_col(position = "dodge",colour='black') +
  scale_x_continuous(breaks = lim,labels = as.character(lim)) +
  coord_cartesian(xlim = c(min(as.numeric(df$value)),max(as.numeric(df$value)))) 
# Theming after this up to you