R ggplot : How can I create conditional labeling for a continuous axis ticks

标签 r ggplot2 conditional axis-labels

我想使用逻辑而非硬编码有条件地更改连续刻度标记标签的颜色/外观/等。例如:

library(tidyverse)
library(viridis)
xx=rpois(1000,lambda = 40)
y=density(xx,n=3600,from=0)

ggplot(data.frame(x = y$x, y = y$y), aes(x, y)) + 
  geom_line() + 
  geom_segment(aes(xend = x, yend = 0, colour = y)) + 
  scale_color_viridis() +
  labs(y='Density',x='Count',colour='Density')+
  geom_vline(xintercept=40,color='red') +
  scale_x_continuous(breaks=c(0,40,seq(25,100,25)),limits=c(0,100))+
  theme(axis.text.x = element_text(face=c('plain','bold',rep('plain',4)),
                                   color=ifelse(y$x==60,'red','black')))

所以在我上面的例子中,硬编码出现在 face 函数中并且有效(我可以对 color 做同样的事情)。这没什么大不了的,因为我只有几次休息时间。不过,在未来的情况下,我的坐标轴可能需要更多的中断或不太简单的着色方案。是否有更有效的解决方案来创建基于条件逻辑的标签?我的第一次尝试是在 color 函数中看到的,但那不起作用。问题是识别要在逻辑语句中使用的对象。也许有一个幕后变量我可以调用中断(类似于使用 ..level.. 绘制密度图)。如果是这样的话,如果你能教我如何找到它/自己弄清楚的话,加分

最佳答案

非常感谢 Djork 教我一些 QnA 礼仪......

我能够通过在 ggplot 之外定义我的断点然后在 theme 函数中使用 ifelse 逻辑来创建我想要的结果来解决这个问题。我的原始代码的更新(和工作)示例如下:

library(tidyverse)
library(viridis)
xx=rpois(1000,lambda = 40)
y=density(xx,n=3600,from=0)

med_x=median(xx)
breakers = c(seq(0,100,25),med_x)

ggplot(data.frame(x = y$x, y = y$y), aes(x, y)) + 
  geom_line() + 
  geom_segment(aes(xend = x, yend = 0, colour = y)) + 
  scale_color_viridis() +
  labs(y='Density',x='Count',colour='Density')+
  geom_vline(xintercept=40,color='red') +
  scale_x_continuous(breaks=breakers,limits=c(0,100))+
  theme(axis.text.x = element_text(face=ifelse(breakers==med_x,'bold','plain'),
                                   color=ifelse(breakers==med_x,'red','black')))

我还没有在更复杂的逻辑上尝试过这种方法,但我认为这种方法适用于所有逻辑格式。

关于R ggplot : How can I create conditional labeling for a continuous axis ticks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49076565/

相关文章:

R Markdown/rmarkdown 中的回归表 (html/pdf)

python - 有没有更有效的方法来聚合数据集并计算 Python 或 R 中的频率?

python - 在没有管理员权限的情况下安装 Python/Matlab 库?

php - 我应该使用正则表达式,还是只使用一系列 if 语句?

swift - 为什么不将 LET 用作可选项会引发错误,因为它是与零的隐式比较 - Swift 介绍书中的不一致?

java - Java中的多线程矩阵乘法

r - 如何快速将矩阵列表乘以向量列表?

r - 当我在散点图中将轴的原点设置为零时,点被切断

if-statement - Shiny 的多个 IF if 语句

r - 如何在ggplot中使用变量指定列名