【问题标题】:Adding odds ratios values and different colors in a ggplot graph in R在 R 的 ggplot 图中添加优势比值和不同颜色
【发布时间】:2021-05-27 18:49:57
【问题描述】:

我正在尝试在图表中插入优势比值。 我也在尝试为具有显着优势比的形状赋予不同的颜色。显着优势比是指置信区间不包含值 1 的那些。 有人可以帮我解决这个问题吗?

我的代码示例是:

df <- data.frame(yAxis = length(boxLabels):1,
boxOdds = c(2.23189,1.315737,1.22866,.8197413,.9802449,.9786673,.6559005,.5929812),
boxCILow = c(.7543566,1.016,.9674772,.6463458,.9643047,.864922,.4965308,.3572142),
boxCIHigh = c(6.603418,1.703902,1.560353,1.039654,.9964486,1.107371,.8664225,.9843584))

绘制图表

ggplot(df, aes(x = boxOdds, y = boxLabels)) +
  geom_vline(aes(xintercept = 1), size = .25, linetype = 'dashed') +
  geom_errorbarh(aes(xmax = boxCIHigh, xmin = boxCILow), size = .5, height = 
      .2, color = 'gray50') +
  geom_point(size = 3.5, color = 'orange') +
  theme_bw() +
  theme(panel.grid.minor = element_blank()) +
  scale_x_continuous(breaks = seq(0,7,1) ) +
  coord_trans(x = 'log10') +
  ylab('') +
  xlab('Odds ratio (log scale)') +
  annotate(geom = 'text', y =1.1, x = 3.5, label ='Model p < 0.001\nPseudo 
R^2 = 0.10', size = 3.5, hjust = 0) + ggtitle('My title')

【问题讨论】:

  • 给定数据中缺少 boxLabels 变量

标签: r ggplot2 plot colors glm


【解决方案1】:

我为 boxLabels 创建了一个虚拟变量,因为您的代码缺少它。

您未来的情节需要注意的一点: 事先定义情节所需的一切。例如详细说明您的测试是否重要的​​变量。

boxLabels <- letters[1:8] # dummy boxlabels variable

df <- data.frame(yAxis = length(boxLabels):1,
    boxOdds = c(2.23189,1.315737,1.22866,.8197413,.9802449,.9786673,.6559005,.5929812),
    boxCILow = c(.7543566,1.016,.9674772,.6463458,.9643047,.864922,.4965308,.3572142),
    boxCIHigh = c(6.603418,1.703902,1.560353,1.039654,.9964486,1.107371,.8664225,.9843584),
    boxLabels = boxLabels # Don't forget to actually put it in the dataframe if you use it in the plot.
) 

# Make a variable for whether your test is significant
df$isSignif <- df$boxCILow > 1 | df$boxCIHigh < 1

g <- ggplot(df, aes(x = boxOdds, y = boxLabels)) +
  geom_vline(aes(xintercept = 1), size = .25, linetype = 'dashed') +
  geom_errorbarh(aes(xmax = boxCIHigh, xmin = boxCILow), size = .5, height = 
      .2, color = 'gray50') +
  geom_point(aes(color = isSignif), size = 3.5) + ## Use the variable to define the color of your plot.
  theme_bw() +
  theme(panel.grid.minor = element_blank()) +
  scale_x_continuous(breaks = seq(0,7,1) ) +
  coord_trans(x = 'log10') +
  ylab('') +
  xlab('Odds ratio (log scale)') +
  annotate(geom = 'text', y =1.1, x = 3.5, label ='Model p < 0.001\nPseudo 
R^2 = 0.10', size = 3.5, hjust = 0) + ggtitle('My title')

# add the oddsRatio values to the plot
g <- g + geom_text(label=round(df$boxOdds, 2), nudge_y=0.25)
g

我从您的代码中更改的唯一行是带有注释的行。

这将输出以下图:

【讨论】:

  • 抱歉,我的数据中确实缺少 boxLabels 变量。非常感谢您的关注和帮助。效果很好!!!
  • 没问题!如果您的问题得到解决,请不要忘记接受答案。
猜你喜欢
  • 1970-01-01
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
相关资源
最近更新 更多