Home > Blockchain >  ggplot2 Expand the plot limits giving error
ggplot2 Expand the plot limits giving error

Time:10-19

I have a df:

test<- data.frame (Metrics = c("PCT_PF_READS (%)" , "PCT_Q30_R1 (%)" , "PCT_Q30_R2 (%)"), 
LowerLimit = c(80,80,80), 
Percent = c(93.1,95.1,92.4) 
)

> test
           Metrics LowerLimit Percent
1 PCT_PF_READS (%)         80    93.1
2   PCT_Q30_R1 (%)         80    95.1
3   PCT_Q30_R2 (%)         80    92.4

I am trying to plot in ggplot2 but I want to specify the yaxis. If I do:

ggplot(data=test3, aes(x= Metrics,y=Percent,))  
  geom_bar(stat="identity" )

without limits

If I try to set the yaxis to start at 75, I get a blank plot:

ggplot(data=test3, aes(x= Metrics,y=Percent,))  
  geom_bar(stat="identity" )   scale_y_continuous(limits = c(75,100))

plot with limits

with the message

Warning message:
Removed 3 rows containing missing values (geom_bar)

But the values are in range????

CodePudding user response:

Does this answer your question?

library(tidyverse)

test<- data.frame (Metrics = c("PCT_PF_READS (%)" , "PCT_Q30_R1 (%)" , "PCT_Q30_R2 (%)"), 
                   LowerLimit = c(80,80,80), 
                   Percent = c(93.1,95.1,92.4) 
)

# Starting plot:
ggplot(data = test, aes(x = Metrics, y = Percent))  
  geom_bar(stat = "identity")


# If you cut off any of the bar using "limit" the bar is removed,
# E.g. this removes the middle bar (Percent = 95.1)
ggplot(data = test, aes(x = Metrics, y = Percent))  
  geom_bar(stat = "identity")  
  scale_y_continuous(limits = c(0,95))
#> Warning: Removed 1 rows containing missing values (position_stack).


# A better solution is to use "coord_cartesian()"
ggplot(data = test, aes(x = Metrics, y = Percent))  
  geom_bar(stat = "identity")  
  coord_cartesian(ylim = c(75, 100))


# Although it's generally advised to keep the whole axis,
# as 'chopping off' the bottom can be misleading

# Another alternative is to write the percentages on the plot:
ggplot(data = test, aes(x = Metrics, y = Percent))  
  geom_bar(stat = "identity")  
  geom_text(aes(label = paste0(Percent, "%")),
            nudge_y = 2)

Created on 2022-10-19 by the reprex package (v2.0.1)

  • Related