【问题标题】:How to plot negative values using ggplot geom_col avoiding values interpolation如何使用 ggplot geom_col 绘制负值避免值插值
【发布时间】:2022-01-06 01:52:14
【问题描述】:

我有以下数据框:

dat <- structure(list(kd_hdp = c(
  -1.30681818181818, -0.896, -0.952,
  -0.952, -1.208, -1.108, -1.108, -1.008
), dose = structure(c(
  3L,
  3L, 3L, 3L, 3L, 3L, 3L, 3L
), .Label = c(
  "0.3mM", "1mM", "3mM",
  "10mM", "20mM"
), class = "factor"), status = structure(c(
  1L,
  4L, 4L, 3L, 1L, 1L, 1L, 2L
), .Label = c(
  "-", "+", "++", "+++",
  "++++"
), class = "factor")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -8L))

数据如下:

> dat
# A tibble: 8 × 3
  kd_hdp dose  status
   <dbl> <fct> <fct> 
1 -1.31  3mM   -     
2 -0.896 3mM   +++   
3 -0.952 3mM   +++   
4 -0.952 3mM   ++    
5 -1.21  3mM   -     
6 -1.11  3mM   -     
7 -1.11  3mM   -     
8 -1.01  3mM   +    

当我用以下代码绘制它时:

library(tidyverse)
ggplot(dat, aes(x = status, y = kd_hdp)) + 
  geom_col() + 
  theme(axis.text.x=element_text(  size = 25), 
        axis.text.y=element_text( size = 25) 
  ) 

我明白了:

请注意,绘图的 y 轴延伸到 &gt; -4,其中 kd_hdp 的最小值是 -1.21。 如何让 ggplot 生成具有精确值作为输入数据的 y 轴?

【问题讨论】:

    标签: r ggplot2 tidyverse


    【解决方案1】:

    在数据中,每个status 都有多个值。您在图中看到的是这些值中的sum

    library(dplyr)
    library(ggplot2)
    
    dat %>% group_by(status) %>% summarise(kd_hdp = sum(kd_hdp))
    
    #  status kd_hdp
    #  <fct>   <dbl>
    #1 -      -4.73 
    #2 +      -1.01 
    #3 ++     -0.952
    #4 +++    -1.85 
    

    您需要在绘图之前决定如何聚合数据。例如,如果您只想考虑 min 值,您可以这样做 -

    dat %>%
      group_by(status) %>%
      summarise(kd_hdp = min(kd_hdp)) %>%
      ggplot(aes(x = status, y = kd_hdp)) + 
      geom_col() + 
      theme(axis.text.x=element_text(  size = 25), 
            axis.text.y=element_text( size = 25) 
      ) 
    

    如果你想分别绘制每个值,你可以这样做 -

    dat %>%
      group_by(status) %>%
      mutate(index = factor(row_number())) %>%
      ggplot(aes(x = status, y = kd_hdp, fill = index)) + 
      geom_col(position = "dodge") + 
      theme(axis.text.x=element_text(  size = 25), 
            axis.text.y=element_text( size = 25) 
      ) 
    

    【讨论】:

      猜你喜欢
      • 2012-08-25
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      • 2023-03-24
      • 2019-02-05
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多