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

在 ggplot2 中自定义特定的 x 轴刻度

如何解决在 ggplot2 中自定义特定的 x 轴刻度

听起来很简单,但我一直在寻找,但一无所获。

我有这个数据:

> df <- data.frame(themes = c("Restoration techniques","Managing projects","Ecology and hydrology","Carbon benefits of peatland"),before = c(2.243243,2.162162,2.135135),after = c(2.366667,2.366667,2.233333))
> df
                       themes   before    after
2      Restoration techniques 2.243243 2.366667
1       Ecology and hydrology 2.162162 2.366667
4 Carbon benefits of peatland 2.162162 2.366667
3           Managing projects 2.135135 2.233333

我是这样绘制的:

ggplot(df) +
  geom_segment(aes(x = fullname,xend = fullname,y = 1,yend = 3),color = "grey") +
  geom_segment(aes(x = fullname,y = before,yend = after),color = "yellowgreen") +
  geom_point(aes(x = fullname,y = before),color = viridis(50)[40],size = 4) +
  geom_point(aes(x = fullname,y = after),color = viridis(50)[25],size = 4) +
  coord_flip() +
  theme_ipsum() +
  xlab("") + ylab("")

结果如下:

enter image description here

我想要的是更改水平轴上的刻度标签

更具体地说,我不想要数字,我想要值为 1 的“低”、值为 2 的“中”和值为 3 的“高”。

我尝试使用scale_x_discrete(),特别添加

+
scale_x_discrete(breaks=c(1,2,3),labels=c("Low","Medium","High"))

但我得到的是下图:

enter image description here

我感觉问题可能出在 x 轴的性质上,但我不知道我应该如何解决问题以及我应该在情节代码添加哪些行。

解决方法

您需要使用 scale_y_continuous() 如下:

ggplot(df) +
  geom_segment(aes(x = themes,xend = themes,y = 1,yend = 3),color = "grey") +
  geom_segment(aes(x = themes,y = before,yend = after),color = "yellowgreen") +
  geom_point(aes(x = themes,y = before),color = viridis(50)[40],size = 4) +
  geom_point(aes(x = themes,y = after),color = viridis(50)[25],size = 4) +
  coord_flip() +
  theme_ipsum() +
  xlab("") + ylab("") + 
  scale_y_continuous(breaks=c(1,2,3),labels=c("Low","Medium","High"))

enter image description here

您必须使用与您拥有的数据的性质相匹配的 scale_ 函数。由于您的 y 轴数据是连续的,因此您需要 scale_y_continuous(),即使您的目标是让它看起来好像是离散的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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”。这是什么意思?