微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?