[R] R facets including two kinds of charts

phii m@iii@g oii phiiipsmith@c@ phii m@iii@g oii phiiipsmith@c@
Thu Aug 1 20:01:56 CEST 2024


I am asking for help with a ggplot2 program that has facets. There are 
actually 100 facets in my program, but in the example below I have 
limited the number to 3. There are two kinds of charts among the facets. 
One kind is a simple line plot with all of the y-values greater than 
zero. The facet for "A" in my example below is this kind. The other kind 
is a line plot combined with a bar chart with some of the y-values being 
positive and others negative. The facets for "B" and "C" in my example 
are this kind.

The facets for "B" and "C" look the way I want them to. However the 
facet for "A" has a scale on the y-axis that starts at zero, whereas I 
would like the minimum value on this scale to be non-zero, chosen by 
ggplot2 to be closer to the minimum value of y for that particular 
facet.

My example may not be the most efficient way to achieve this, but it 
works except for one aspect. Chart A, for which I do not wish to show a 
zero line, does indeed not show a zero line but it nevertheless chooses 
a scale for the y-axis that has a minimum value of zero. How can I 
adjust the code so that it chooses a minimum value on the y-axis that is 
non-zero and closer to the minimum actual y-value (as would be the case 
for a simple line chart alone, without any facets)?

library(ggplot2)
library(dplyr)

df <- data.frame(
   date=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6),
   
nm=c("A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C"),
   val0=c(NA,-5,4,NA,-3,3,NA,2,4,NA,3,3,NA,3,1,NA,-3,-4),
   val1=c(NA,-3,6,NA,-1,4,NA,5,5,NA,7,2,NA,4,3,NA,-2,-2),
   val2=c(50,NA,NA,53,NA,NA,62,NA,NA,56,NA,NA,54,NA,NA,61,NA,NA),
   zline=c(NA,0,0,NA,0,0,NA,0,0,NA,0,0,NA,0,0,NA,0,0)
)

ggplot(df)+
   geom_col(aes(x=date,y=val0),na.rm=TRUE,fill="white")+
   geom_line(aes(x=date,y=val1))+
   geom_line(aes(x=date,y=val2))+
   geom_hline(aes(yintercept=zline),na.rm=TRUE)+
   facet_wrap(~nm,scales="free_y")

Thank you for your assistance.

Philip



More information about the R-help mailing list