How to plot negative values using ggplot geom_col avoiding values interpolation

Viewed 78

I have the following data frame:

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))

The data looks like this:

> 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   +    

When I plot it with the following code:

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) 
  ) 

I get this:

enter image description here

Notice that the y-axis of the plot extends to > -4 where as the lowest value of kd_hdp is -1.21. How can I make ggplot to produce y-axis with exact value as the input data?

1 Answers

In the data there are multiple values for each status. What you are seeing in the plot is sum of those values.

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 

You need to decide how you want to aggregate the data before plotting. For example, if you want to consider only the min value you can do -

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) 
  ) 

enter image description here

If you want to plot each value separately you may do -

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) 
  ) 

enter image description here

Related