r - 显示 x 轴中断的 y 值

标签 r ggplot2

我想突出显示将 y 值文本添加到绘图中,但仅限于我设置 x 轴中断的那些点。在我的原始数据中,x值是离散的,但为了简单起见,让我们使用从0到125的序列作为示例,我希望我可以自己转移我的数据的解决方案。 如果我简单地说

... + geom_text(aes(label=y),size=3) + ...

这会导致无法读取的困惑。例如

enter image description here

这就是我的绘图代码和示例数据的样子。

data %>%
  group_by(x) %>%  
  summarise(y= sum(y,na.rm = TRUE)) %>% 
  ggplot( aes(x=x,y=y,group=1)) + 
  scale_x_continuous(breaks = c(1,50,75,100,125))+   
  geom_text(aes(label = y), size = 3)+
  geom_line()


# while the data after summarised looks somethat like this
x <- seq(1,125,1)
y <- x^2
data <- data.frame(cbind(x,y))

非常感谢您的所有回复。 亲切的问候

EDIT: In my comments I referred to "strange behavior" and I just wanted to show you what happens on my real data.

strange things happen here

使用标记答案时不会发生这种情况。

最佳答案

您可以将带有标签的列添加到数据集,而不是使用“第二个”数据框作为标签。正如我从 Thomas Lin Pedersen 的 ggplot2 研讨会上了解到的,这种方法更通用,例如如果您想使用 ggrepel 包中的 geom_text_repel

library(dplyr)
library(ggplot2)

x <- seq(1,125,1)
y <- x^2

dat <- data.frame(cbind(x,y))

dat %>%
  group_by(x) %>%  
  summarise(y= sum(y,na.rm = TRUE)) %>% 
  mutate(label = ifelse(x %in% c(1,50,75,100,125), y, "")) %>% 
  ggplot( aes(x=x,y=y,group=1)) + 
  scale_x_continuous(breaks = c(1,50,75,100,125))+   
  geom_text(aes(label = label), size = 3)+
  geom_line()

reprex package于2020年4月4日创建(v0.3.0)

关于r - 显示 x 轴中断的 y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61025836/

相关文章:

r - 提供参数的惰性求值

r - 截断字符串(不截断单词)

r - 根据以 ocr'd 图像结尾的段落将字符串拆分为列

r corrplot 与聚类 : default dissimilarity measure for correlation matrix

r - 使用ggplot获取带有百分比标签的条形图的最有效方法

r - 将ggplot2中的十六进制垃圾箱设置为相同大小

r - 结合 geom_boxplot 和 geom_line

R ggplot facet_grid_sc 与 cols

r - 使用 ggplot 移动绘图

r - 在ggplot中对齐绘图区域